2

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

4

1 回答 1

4
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
于 2013-07-25T04:57:30.057 回答