Nested has_many :through relations fixed in 2.1.0?

Searching on google yields quite a lot of results describing the following problems:

class Person < ActiveRecord::Base   belongs_to :house end

class House < ActiveRecord::Base   has_many :people   belongs_to :city end

class City < ActiveRecord::Base   has_many :houses   has_many :people, :through => :houses   belongs_to :country end

class Country < ActiveRecord::Base   has_many :cities   has_many :houses, :through => :cities end

So far so good. Yet, I want to know all the people living in a country. Creating the following has_many :through relation yields an error on call: has_many :people, :through => :houses in the Country class. With the abovementioned code this is only possible by iterating through all coutry.houses and collecting the house.people.

Aparently in 2006 and 2007 alot of people walked into the same problems, yet in Rails 2.1.0 I am still unable to make said relation. Is this bug still not fixed, or am I doing something wrong in calling it?

Hi, which statement generates the error? Do you have foreign keys on both House and City models? If not, you should have the following foreign keys:

City: country_id, house_id

House: city_id, person_id

From the above, your join models are House and City. Thus, I would recommend working with your City, House, and Person models first. For example, you should be able to answer the following questions:

Who lives in CityA?

city = City.find_by_name( ‘CityA’ )

residents = city.people

Which City does John live?

john = Person.find_by_name( ‘John’ )

city =

Note: When attempting to answer these questions, both ends of the association must have been saved (i.e. committed to the database). For example, you’ll need to do the following:

person = Person.create( :name => ‘John’ )

city = City.create( :name => ‘Chicago’ )

city.people << person

After you get this working, then you can start to play with the Country, City, and House models. For example, you should be able to answer the following questions:

What houses are in CountryA?

and so on

Good luck,