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?