views:

186

answers:

2

What I'd like to do is join one model to another using two intermediary models in between..Here's the abstraction:

Country has_many Companies
Company has_many Buildings, Company belongs_to Country
Building has_many Rooms, Building belongs_to Company
Room belongs_to Building

I want to be able to do Country.first.rooms, so I thought the Country model would be as simple as:

class Country - ActiveRecord::Base
    has_many :companies
    has_many :buildings, :through=>:companies
    has_many :rooms, :through=>:buildings
end

However, this tries to generate SQL like: SELECT * FROM rooms INNER JOIN buildings ON rooms.building_id = building.id WHERE ((building.country_id = 1))

Obviously, building.country_id does not exist...how do I get around this?

+1  A: 

The built in association methods won't help you here. You need to build the query explicitly using joins:

class Country - ActiveRecord::Base

    has_many :companies
    has_many :buildings, :through=>:companies

    def rooms
      Room.all :joins => { :building => { :company => :country } }, :conditions => { "countries.id" => id }
    end

end

This will require the belongs_to associations to be set up on the Building and Company models

derfred
With that, I get an error saying:ActiveRecord::ConfigurationError: Association named 'country' was not found; perhaps you misspelled it?I'm guessing it's because "building", which is one model removed from country (they are associated by "Company", which explicitly belongs to a Country) is only implicitly related to country.
Dan
youre right i missed that
derfred
A: 

Try using nested has many through

austinfromboston