Eager loading with has_many :through


#1

I’ve got the following associations:

class Photo < AR::Base
has_many :slides
has_many :albums, :through => :slides

this has an attachment_fu attachment which creates a thumbnail

image for each uploaded photo.
end

class Album < AR::Base
has_many :slides
has_many :photos, :through => :slides
end

class Slide < AR::Base
belongs_to :photo
belongs_to :album
end

In my Photos#index action I render all thumbnails and list the albums
that the photos belong to. I’m using attachment_fu, the parent image
is the one with the slide and album association, the thumbnail image
does not have that association.

The index action is hitting the database to load all albums that
belong to a photo, how can I cut that down to one query for eager
loading?

Currently I’m doing:

Photo.find(:all, :include => :parent, :conditions [‘thumbnail = ?’,
‘small’])

but I can’t figure out how to eager-load the albums, through slides,
based on the parent photo (since the thumbnail doesn’t have any
associated slides or albums.)

Thanks for any help,

Stu


#2

On Feb 25, 4:46 am, shenry removed_email_address@domain.invalid wrote:

Currently I’m doing:

Photo.find(:all, :include => :parent, :conditions [‘thumbnail = ?’,
‘small’])

but I can’t figure out how to eager-load the albums, through slides,
based on the parent photo (since the thumbnail doesn’t have any
associated slides or albums.)

You can nest includes, eg Photo.find :all, :include => {:parent =>
[:some_association_on_parent, :another_association_on_parent]}

Fred


#3

Sweet, thanks Fred.

On Feb 25, 12:02 am, Frederick C. removed_email_address@domain.invalid