Rails associations across multiple levels

I am relatively new to Rails and am working on a project that includes several “nested” data layers. I'm having trouble creating the appropriate associations, so I can get all the children of a level 3 model higher. Here is an example of 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

I implemented a connection in a model Country, has_many :cities, :through => :statesand tried to call Country.first.cities.allwhich works. However, I am having problems accessing all the people in this country when I try to execute Country.first.cities.all.people.allin the controller People.

? , country_id, People Country? .

+3
2

, Country.first.cities.all - , people, . , :

Country.first.cities.first.people.all

. , :

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

beacouse

Country.first.cities.all

, .

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

Source: https://habr.com/ru/post/1795084/


All Articles