Forum: Ruby on Rails eager loading with has_many :through

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
shenry (Guest)
on 2009-02-25 06:47
(Received via mailing list)
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
Frederick C. (Guest)
on 2009-02-25 10:03
(Received via mailing list)
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
shenry (Guest)
on 2009-02-25 17:54
(Received via mailing list)
Sweet, thanks Fred.

On Feb 25, 12:02 am, Frederick C. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.