:include doesn't work with belongs_to

I’m having issues getting :include to eagerly load data in a
“belongs_to” association. Here’s the breakdown:

Users have friends and an avatar image. If I am loading all the
user’s friends I want to also eagerly load the images for those users
in the same SQL query – instead of 1 query per friend, which adds up
quickly. Here are my models:

Image
belongs_to :imageable, :polymorphic => true

User
has_many :images, :as => :imageable
has_many :friends, :include => :user,

Friend
# The user
belongs_to :owner_user,
:class_name => “User”,
:foreign_key =>“user_id”,

# The friend
belongs_to :user,
                 :class_name => "User",
                 :foreign_key => "friend_id",
                 :include => :images

As you can see I use :include on User#friends for “user” and then on
Friend#user for “images”. My thinking is, when accessing
User#friends, rails will eagerly load the User object for each friend
and all the images for that user.

friend -> user -> images

Currently the first part works (friend -> user), but it does not query
for the images at the same time. So when I list all a user’s friends
with their avatars I get a lot of SQL queries.

What am I doing wrong? How can I optimize this?

Mozmonkey wrote:

I’m having issues getting :include to eagerly load data in a
“belongs_to” association. Here’s the breakdown:

I believe there is a known bug with eager loading and belongs_to. I just
can’t find the ticket in trac.


Josh S.
http://blog.hasmanythrough.com

Is there any work around that you can think of?

Thanks!
Jeremy

I thought the known problem was the other way round?

ie if I’m loading some Images and i want to include :imageable then
we’re stuck (because we don;t know which tables to join on, and even
if you do it would probably be rather ineffecient. (There is a patch
out there (blowing my own horn for a second:
http://dev.rubyonrails.org/ticket/9640),
which does address this (although mainly as a side effect of
completely replacing :include)). You can get this by hand: give the
array of things, find the distinct types and do one query per type.

In this case you do get a warning about not being able to :include the
polymorphic association. I thought the other way round was ok though.
The code in associations.rb certainly looks like it’s trying to handle
it.

Fred

OK, so using polymorphic is what breaks this? So should is it more
efficient to have different Models for different image types? I’ll
also go checkout your solution right now.