我有一个模型Couple
,它有两列first_person_id
和second_person_id
以及另一个模型Person
,其主键为person_id
和列name
这是我想要的用法:
#including 'Person' model for eager loading, this is crucial for me
c = Couple.find(:all, :include => :persons)[0]
puts "#{c.first_person.name} and #{c.second_person.name}"
那我怎么能这样做呢?
答案 0 :(得分:14)
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
。如果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
如果Person
可以属于多个Couple
,并且无法确定它们是否是任何给定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
答案 1 :(得分:0)
未经测试,但根据Rails API documentation,可能类似于:
class Couple < ActiveRecord::Base
has_one :person, :foreign_key => :first_person_id
has_one :person, :foreign_key => :second_person_id
end
答案 2 :(得分:0)
仅限理论,未经测试:
创建Person的两个子类:
class FirstPerson < Person
belongs_to :couple
class SecondPerson < Person
belongs_to :couple
每个人都有几个班级:
class Couple
has_many :first_persons, :foreign_key => :first_person_id
has_many :second_persons, :foreign_key => :second_person_id
然后找到:
Couple.all(:include => [:first_persons, :second_persons])