通过两种不同的方式访问has_many关系ActiveRecord Rails [英] access has_many relation in two different ways ActiveRecord Rails
问题描述
我需要以两种方式进入机构. 我的模型如下:
I need to access institution in two ways. My models are given below:
class Person < ActiveRecord::Base
has_many :institution_people
has_many :institution_choices
has_many :institutions, :through => :institution_people
has_many :institutions, :through => :institution_choices
fields........
end
class Institution < ActiveRecord::Base
has_many :people, :through => :institution_people
has_many :people, :through => :institution_choices
has_many :institution_people
has_many :institution_choices
end
class InstitutionChoice < ActiveRecord::Base
belongs_to :person
belongs_to :institution
end
class InstitutionPerson < ActiveRecord::Base
belongs_to :person
belongs_to :institution
end
我设置像这样的模型是因为人们可以在不同的机构学习,所以为此我设置
The i setup the models like this is that person can study in different institutions, so for this i setup
has_many :institutions, :through => :institution_people
用于人物模型
但是同时人们可以选择机构,所以我设置了
But at the same time person can have institution choices, so i setup
has_many :institutions, :through => :institution_choices
用于人员模型.
我应该如何设置人与机构之间的模型和关联,以便可以从两种方式从人中找到机构.
How should i setup model and association between person and institutions so that i can find institutions from person in both ways.
现在
Person.first.institutions
从stitutional_people表中查找,就像
finds from institution_people table, as
has_many :institutions, :through => :institution_people
我猜是刚开始.
欢迎使用其他一些技术,这样我就可以通过两种方式建立机构.
Some other techniques are welcomed so that i can get institutions in both ways.
推荐答案
在您的Person
模型中,尝试以下操作:
In your Person
model, try this :
class Person < ActiveRecord::Base
has_many :institution_people
has_many :institution_choices
has_many :institutions_people, :through => :institution_people, :source => :institutions, :class_name => "Institution"
has_many :institutions_choices, :through => :institution_choices, :source => :institutions, :class_name => "Institution"
end
http://guides.rubyonrails.org/association_basics.html#has_many-关联参考
这篇关于通过两种不同的方式访问has_many关系ActiveRecord Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!