如何设置Rails关联,其中一个模型属于另一个模型的两个实例?

时间:2012-05-16 14:37:28

标签: ruby-on-rails-3 activerecord

我有两个模型ObjectA和ObjectB。 ObjectB有两列,a_1_id和a_2_id,它们都是ObjectA的外键。 ObjectB属于这些外来ObjectA对象中的每一个。

class ObjectA < ActiveRecord::Base
  attr_accessible :player_1, :player_2, :subject, :turn

  belongs_to :player_1, :class_name => "User"
  belongs_to :player_2, :class_name => "User"
  has_many :object_b, dependent: :destroy, :finder_sql => "SELECT * FROM object_bs where (a_1_id = #{id} or a_2_id = #{id})" 
end

class ObjectB < ActiveRecord::Base
  attr_accessible :a_1_id, :a_2_id

  belongs_to :a_1_id, :class_name => "ObjectA"
  belongs_to :a_2_id, :class_name => "ObjectA"
end

这是设置关联的最佳方式吗?

1 个答案:

答案 0 :(得分:1)

使用:foreign_key选项:

belongs_to :player_1, :class_name => "User", :foreign_key => 'player1_id'
belongs_to :player_2, :class_name => "User", :foreign_key => 'player2_id'
#...
belongs_to :a_1_id, :class_name => "ObjectA", :foreign_key => 'a_1_id'
belongs_to :a_2_id, :class_name => "ObjectA", :foreign_key => 'a_2_id'