7

Couple2つの列を持つモデルと、およびfirst_person_id主キーが列を持つsecond_person_id別のモデルがあります。Personperson_idname

これが私が望む使用法です:

#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 ...>>

それらは、 aが複数の一部になることができるPersonかどうかによって異なります。が1つだけに属することができ、一方と他方の「最初」になることができない場合は、次のようにすることができます。PersonCouplePersonCouplePersonSecond

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
于 2010-01-25T22:56:57.887 に答える
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 に答える
0

理論のみ、テストされていません:

Personの2つのサブクラスを作成します。

class FirstPerson < Person
   belongs_to :couple

class SecondPerson < Person
   belongs_to :couple

カップルクラスhas_manyofeach:

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 に答える