Question

I need to create an has_many :through association where one foreign key is not the model id but the name

class User < ActiveRecord::Base  
  has_many :ownerships
  has_many :articles, :through => :ownerships
end

class Article < ActiveRecord::Base  
  has_many :ownerships
  has_many :users, :through => :ownerships
end

class Ownership < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end




create_table "ownerships", :force => true do |t|
    t.integer  "user_id"
    t.string   "article_code"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I have tried assigning foreign_keys to the associations but without luck.

Is there a way to achieve my goal using the built-in RoR associations?

No correct solution

OTHER TIPS

class Article < ActiveRecord::Base  
  has_many :ownerships, :foreign_key => :article_code, :primary_key => "code"
  has_many :users, :through => :ownerships
end

class Ownership < ActiveRecord::Base
  belongs_to :user
  belongs_to :article, :foreign_key => :article_code, :primary_key => "code"

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top