Has_many :through


#1

I have:

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

What is the query RoR is using when I type:

@places = @country.places

Is it only one query with joins?


#2

Wiktor wrote:

@places = @country.places

Replying to myself…

It doesn’t seem to work - cascading :through doesn’t work :frowning:
Or am I doing something wrong?


#3

Well for a start I think you’ve misunderstood the usage of has_many
:through. The idea is that its a different way of writing
has_and_belongs_to_many. Your model should be:

class Country < ActiveRecord::Base
has_many :states
end

class State < ActiveRecord::Base
has_many :cities
end

class City < ActiveRecord::Base
has_many :places
end

Hope this helps.
-Nathan