ActiveRecord的的has_many凡在表中的两列是表B中的主键 [英] ActiveRecord has_many where two columns in table A are primary keys in table B

查看:180
本文介绍了ActiveRecord的的has_many凡在表中的两列是表B中的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,夫妻,其中有两列, first_person_id second_person_id 和另一种模式,,其主键是为person_id 并具有列名称

I have a model, Couple, which has two columns, first_person_id and second_person_id and another model, Person, whose primary key is person_id and has the column 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}"

所以,我该怎么办呢?

So how can I do this?

推荐答案

在声明的关系夫妻应该是这样的:

The relationships declared in Couple should look like this:

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

那些在取决于是否能成为其中的一部分多个情侣。如果只能属于一个夫妻并不能成为第一上一个和在另一个,你可能想:

Those in Person depend on whether a Person can be part of more than one Couple. If a Person can only belong to one Couple and can't be the "first" Person on one and the Second on another, you might want:

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

如果一个可以属于多个夫妻 S,而且也没有办法告诉他们是否是在第一次,或在任何给定的夫妻,你可能要第二:

If a Person can belong to several Couples, and there's no way to tell whether they're the "first" or "second" in any given Couple, you might want:

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

这篇关于ActiveRecord的的has_many凡在表中的两列是表B中的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆