1

我有两个模型 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

这是建立协会的最佳方式吗?

4

1 回答 1

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'
于 2012-05-16T14:41:32.257 回答