ActiveRecord has_many其中表A中的两列是表B中的主键

use*_*154 7 ruby activerecord ruby-on-rails has-many

我有一个模型,Couple,其中有两列,first_person_idsecond_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}"
Run Code Online (Sandbox Code Playgroud)

那我该怎么做呢?

Jam*_*sen 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 ...>>
Run Code Online (Sandbox Code Playgroud)

那些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
Run Code Online (Sandbox Code Playgroud)

如果a Person可以属于多个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
Run Code Online (Sandbox Code Playgroud)