artists have many activities (basically a cache of interactions between users):
class Activity < ActiveRecord::Base
belongs_to :receiver, :class_name => 'Artist', :foreign_key => :receiver_id #owns the stuff done "TO" him
belongs_to :link, :polymorphic => true
belongs_to :creator, :class_name => 'Artist', :foreign_key => :creator_id #person who initiated the activity
end
For example:
Activity.create(:receiver_id => author_id, :creator_id => artist_id, :link_id => id, :link_type => 'ArtRating')
I want to create an activity stream page for each artist, consisting of a list of different types of events, ArtRatings (likes, dislikes), Favoriting, Following etc.
The controller looks like this:
class ActivityStreamController < ApplicationController
def index
@activities = @artist.activities.includes([:link,:creator,:receiver]).order("id DESC").limit(30)
end
end
The db call correctly eagerly loads the polymorphic link objects:
SELECT "activities".* FROM "activities" WHERE (("activities"."receiver_id" = 6 OR "activities"."creator_id" = 6)) ORDER BY id DESC LIMIT 30
ArtRating Load (0.5ms) SELECT "art_ratings".* FROM "art_ratings" WHERE "art_ratings"."id" IN (137, 136, 133, 130, 126, 125, 114, 104, 103, 95, 85, 80, 73, 64)
SELECT "follows".* FROM "follows" WHERE "follows"."id" IN (14, 10)
SELECT "favorites".* FROM "favorites" WHERE "favorites"."id" IN (25, 16, 14)
But when I display each ArtRating, I also need to reference the post title, which belongs to a post. In the view, if I do:
activity.link.post
It does a separate DB call for each art_rating's post. Is there a way to eagerly load the post as well?
UPDATE TO THE QUESTION:
If there is no way to achieve eager loading of posts using 'includes' syntax, is there a way to manually do the eager loading query myself and inject it into the @activities object?
I see in the DB log:
SELECT "art_ratings".* FROM "art_ratings" WHERE "art_ratings"."id" IN (137, 136, 133, 130, 126, 125, 114, 104, 103, 95, 85, 80, 73, 64)
Is there a way I can access this list of ids from the @activities object? If so, I could do 2 additional queries, 1 to get the art_ratings.post_id(s) in that list, and another to SELECT all posts IN those list of post_ids. Then somehow inject the 'post' results back into @activities so that it's available as activity.link.post when I iterate through the collection. Possible?