我需要创建一个 has_many :through 关联,其中一个外键不是模型 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 关联来实现我的目标?
最佳答案
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
关于ruby-on-rails - has_many 通过与 id 以外的键关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848908/