gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:57:20 27 4
gpt4 key购买 nike

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

那我该怎么做呢?

最佳答案

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取决于是否 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

如果 Person可以属于几个 Couple s,并且没有办法判断它们是任何给定 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

关于ruby-on-rails - ActiveRecord has_many 其中表 A 中的两列是表 B 中的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2125440/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com