我需要创建一个has_many:通过关联,其中一个外键不是模型ID而是名称
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
我已经尝试将foreign_keys分配给关联但没有运气。
有没有办法使用内置的RoR关联来实现我的目标?
答案 0 :(得分:2)
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