で宣言された関係は次の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 ...>>
それらは、 aが複数の一部になることができるPerson
かどうかによって異なります。が1つだけに属することができ、一方と他方の「最初」になることができない場合は、次のようにすることができます。Person
Couple
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
aPerson
が複数のに属することができCouple
、それらが特定の「最初」であるか「2番目」であるかを判断する方法がない場合は、次のよう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