Rails的协会通过多层次 [英] Rails Associations Through Multiple Levels
问题描述
我是比较新的Rails和我的工作有关,涉及到数据的多个嵌套级别的项目。我有做适当的关联,以便我能得到一个模型3个级别更高的所有子元素的问题。这里是模型的一个示例:
I am relatively new to Rails and am working on a project that involves multiple, "nested" levels of data. I am having issues making the proper associations so I can get all the child elements of a model 3 levels higher. Here is an example of the models:
class Country < ActiveRecord::Base
has_many :states
end
class State < ActiveRecord::Base
belongs_to :country
has_many :cities
end
class City < ActiveRecord::Base
belongs_to :state
has_many :people
end
class Person < ActiveRecord::Base
belongs_to :city
end
我已经实现了国家
模式,的has_many的关系:城市:通过=&GT; :美国
并试图调用 Country.first.cities.all
,其工作方式。不过,我在访问所有的人在特定的国家,当我尝试的问题 Country.first.cities.all.people.all
在人物
控制器。
I have implemented a relationship in the Country
model, has_many :cities, :through => :states
and have tried to call Country.first.cities.all
, which works. However, I am having issues accessing all the people in a given country when I try Country.first.cities.all.people.all
in the People
controller.
什么是处理这种情况的关联的最好方法?我要补充一个外键给每个孩子表,如 COUNTRY_ID
,让我可以得到所有的人
在国家
?任何建议将是AP preciated。
What is the best way to deal with this sort of association situation? Should I add a foreign key to each of the children tables, such as country_id
, so that I can get all the People
in a Country
? Any suggestions would be appreciated.
推荐答案
的原因在于Country.first.cities.all是一个数组,并且每个这元件具有方法的人,而不是城市的整个集合。你会发现,这个作品:
The reason is that Country.first.cities.all is an array, and each of it's elements has the method people, instead of the entire collection of cities. You'll notice that this works:
Country.first.cities.first.people.all
由于第一个国家的第一个城市拥有人的方法。为了得到一个国家的所有的人的名单,你可以做一个单一查询以下内容:
Because the first city of the first country has the people method. To get a list of all people in a country, you could do the following in a single query:
People.joins(:city => {:state => :country})
.where(:country => {:id => Country.first.id}).all
这篇关于Rails的协会通过多层次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!