7

我有一个模型,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}"

那么我该怎么做呢?

4

3 回答 3

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取决于 a 是否Person可以是多个a 的一部分Couple。如果 aPerson只能属于一个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可以属于多个Couples,并且无法判断它们是任何给定的“第一”还是“第二” 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
于 2010-01-25T22:56:57.887 回答
0

仅理论,未经测试:

创建 Person 的两个子类:

class FirstPerson < Person
   belongs_to :couple

class SecondPerson < Person
   belongs_to :couple

夫妇类 has_many 每个:

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])
于 2010-01-24T03:37:14.853 回答
0

未经测试,但根据Rails API 文档,可能类似于:

class Couple < ActiveRecord::Base
    has_one :person, :foreign_key => :first_person_id
    has_one :person, :foreign_key => :second_person_id
end
于 2010-01-24T01:07:25.993 回答