MichaelHajuddah
MichaelHajuddah

Reputation: 557

Active Record has_many relationship three levels deep?

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

Answers (3)

Dmitry Matveev
Dmitry Matveev

Reputation: 5376

What you need is

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

Ross Allen
Ross Allen

Reputation: 44880

Without using :through, you would need to iterate over each City and find its zipcodes:

State.first.cities.map(&:zipcodes)

Upvotes: 0

usha
usha

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

Related Questions