has_many通过与id以外的键的关联

时间:2013-07-25 04:16:56

标签: ruby-on-rails associations

我需要创建一个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关联来实现我的目标?

1 个答案:

答案 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