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}]

On 18 May 2008, at 14:03, Sascha Konietzke wrote:

has_many :states
end
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 C. wrote:

On 18 May 2008, at 14:03, Sascha Konietzke wrote:

has_many :states
end
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

Hi Fred,

it works now. Many Thanks!

Sascha

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs