Rails Associations Through Multiple Levels

百般思念 提交于 2019-12-06 03:28:54

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

It's beacouse

Country.first.cities.all

is a collection of cities and it doesn't have people method.

You should go with

Country.first.cities.all.each do |city|
    city.people
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!