Reputation: 5916
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?
Upvotes: 2
Views: 3452
Reputation: 3406
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
Upvotes: 4