Reputation: 557
class State < ActiveRecord::Base
has_many :cities
end
class City < ActiveRecord::Base
has_many :zipcodes
belongs_to :state
end
class Zipcode < ActiveRecord::Base
belongs_to :city
end
When I try doing:
State.first.cities.zipcodes
I get an ActiveRecord::Associations::CollectionProxy
error.
Does anyone know how to go multiple levels deep using the has_many relationship? I did get this working using the through:
option, but is there anyway to do it without using the through:
option?
Upvotes: 1
Views: 967
Reputation: 5376
Add another association clause to you city class like this
class State < ActiveRecord::Base
has_many :cities
has_many :zipcodes, through: :cities
end
then you can just call
state.zipcodes
which will return all zipcodes for a given state (via associated cities)
Upvotes: 5
Reputation: 44880
Without using :through
, you would need to iterate over each City and find its zipcodes:
State.first.cities.map(&:zipcodes)
Upvotes: 0
Reputation: 29349
Do this
State.first.cities.first.zipcodes
This is because State.first.cities
returns a collection since its a has_many relationship between state and city
Upvotes: 0