ruby-on-rails – ActiveRecord has_many其中表A中的两列是表B中的主键

我有一个模型,Couple,它有两列,first_person_id和second_person_id,另一个模型是Person,其主键是person_id并且具有列名

这是我想要的用法

#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}"

那我该怎么做呢?

解决方法

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

那些人在哪里取决于一个人是否可以成为一对夫妻的一部分.如果一个人只能属于一对夫妻而且不能成为一个人的“第一”人,而另一个人就不能成为第二人,你可能想要:

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

如果一个人可以属于几个情侣,并且无法判断他们在任何一对情侣中是“第一个”还是“第二个”,您可能需要:

class Person
  has_many :couples_as_first_person,:class_name => 'Couple'
  has_many :couples_as_second_person,:class_name => 'Couple'

  def couples
    couples_as_first_person + couples_as_second_person
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...