Eager loading multi-level belongs_to

Hi,

I am working on a new project (Rails 2.0.2) and this is driving me nuts. I would appreciate any help!

I have the following classes:

class Nation < ActiveRecord::Base   has_many :states end

class State < ActiveRecord::Base   has_many :cities   belongs_to :nation end

class City < ActiveRecord::Base   has_many :events   belongs_to :state end

class Event < ActiveRecord::Base   belongs_to :city end

The chain for this is event.city.state.nation. When fetching all the events I want to eager-load the belongs_to associations from the database.

I am trying to do this: Event.find(:all, :include => [ {:nation =>{:city => :state}}]

I get this: Association named 'nation' was not found; perhaps you misspelled it?

I would greatly appreciate any help.

Thanks, Sascha

I forgot to mention, doing this one level deep works:

Event.find(:all, :include => [{:city => :state}]

Hi,

I am working on a new project (Rails 2.0.2) and this is driving me
nuts. I would appreciate any help!

I have the following classes:

class Nation < ActiveRecord::Base has_many :states end

class State < ActiveRecord::Base has_many :cities belongs_to :nation end

class City < ActiveRecord::Base has_many :events belongs_to :state end

class Event < ActiveRecord::Base belongs_to :city end

The chain for this is event.city.state.nation. When fetching all the events I want to eager-load the belongs_to associations from the database.

I am trying to do this: Event.find(:all, :include => [ {:nation =>{:city => :state}}]

That tries to eager load the nation association from event, event
doesn't have such an association (or in other words, you're doing
things backwards)

Something along the lines of :include => {:city => {:state
=> :nation}} should do what you want.

Fred

Frederick Cheung wrote: