中声明的关系Couple
应该看起来像这样:
class Couple
named_scope :with_people, { :include => [:first_person, :second_person] }
belongs_to :first_person, :class_name => 'Person'
belongs_to :second_person, :class_name => 'Person'
end
#usage:
Couple.with_people.first
# => <Couple ... @first_person: <Person ...>, @second_person: <Person ...>>
那些在Person
取决于是否Person
可以是多个的一部分Couple
. If a Person
只能属于一个Couple
并且不能成为“第一”Person
上一和Second
另一方面,您可能想要:
class Person
has_one :couple_as_first_person, :foreign_key => 'first_person_id', :class_name => 'Couple'
has_one :couple_as_second_person, :foreign_key => 'second_person_id', :class_name => 'Couple'
def couple
couple_as_first_person || couple_as_second_person
end
end
If a Person
可以属于多个Couple
s,并且无法判断它们是任何给定中的“第一”还是“第二”Couple
, 你可能想要:
class Person
has_many :couples_as_first_person, :foreign_key => 'first_person_id', :class_name => 'Couple'
has_many :couples_as_second_person, :foreign_key => 'second_person_id', :class_name => 'Couple'
def couples
couples_as_first_person + couples_as_second_person
end
end