The relationships declared in Couple
should look like this:
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 ...>>
Those in Person
depend on whether a Person
can be part of more than one Couple
. If a Person
can only belong to one Couple
and can't be the "first" Person
on one and the Second
on another, you might want:
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
can belong to several Couple
s, and there's no way to tell whether they're the "first" or "second" in any given Couple
, you might want:
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
id
but that's not a difficult fix. Just useset_primary_key
. – Pardner