通过多个级别的Rails关联

我对Rails相对较新,正在开发一个涉及多个“嵌套”数据级别的项目。 我在制定正确的关联方面存在问题,因此我可以将模型的所有子元素提高3级。 以下是模型的示例:

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 

我已经在Country模型中实现了一个关系, has_many :cities, :through => :states并且尝试调用Country.first.cities.all ,这有效。 但是,当我在People控制器中尝试Country.first.cities.all.people.all时,我在访问给定国家/地区的所有人时遇到问题。

处理这种关联情况的最佳方法是什么? 我应该为每个子表添加一个外键,例如country_id ,以便我可以获取一个Country所有People ? 任何建议,将不胜感激。

原因是Country.first.cities.all是一个数组,它的每个元素都有方法people,而不是整个城市集合。 您会注意到这有效:

 Country.first.cities.first.people.all 

因为第一个国家的第一个城市有人民的方法。 要获取国家/地区中所有人的列表,您可以在单个查询中执行以下操作:

 People.joins(:city => {:state => :country}) .where(:country => {:id => Country.first.id}).all 

这是beacouse

 Country.first.cities.all 

是一个城市的集合,它没有人的方法。

你应该去

 Country.first.cities.all.each do |city| city.people end