ruby-on-rails – ActiveRecord has_many其中表A中的两列是表B中
发布时间:2020-12-17 04:20:08 所属栏目:百科 来源:网络整理
导读:我有一个模型,Couple,它有两列,first_person_id和second_person_id,另一个模型是Person,其主键是person_id并且具有列名 这是我想要的用法: #including 'Person' model for eager loading,this is crucial for mec = Couple.find(:all,:include = :persons)[
我有一个模型,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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |