通过多个级别的Rails协会

the*_*dym 3 model ruby-on-rails associations hierarchy

我是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
Run Code Online (Sandbox Code Playgroud)

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

处理这种关联情况的最佳方法是什么?我是否应该向每个子表(例如)添加外键country_id,以便将所有内容都包含People在其中Country?任何建议,将不胜感激。

Pan*_*kos 5

原因是Country.first.cities.all是一个数组,并且每个元素都使用people方法,而不是整个城市集合。您会注意到这可行:

Country.first.cities.first.people.all
Run Code Online (Sandbox Code Playgroud)

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

People.joins(:city => {:state => :country})
  .where(:country => {:id => Country.first.id}).all
Run Code Online (Sandbox Code Playgroud)