I’m trying to eager-load Comments when querying my Activity table.
# Activity (basic FB-style news feed)
# user_id
# primary_source_id (polymorphic object, like "Post", that can have comments)
# primary_source_type
# Comment (acts as commentable w/ threading gem)
# user_id
# commentable_id
# commentable_type
# WHAT GOES HERE?!
# How do I eager-load comments?
activities = Activity.includes(???).joins(???)
# Display code
activities.each do |activity|
render ... # render activity
activity.root_comments.each do |comment|
render ... # render activity's comments
end
end
See, I render my page by looping through Activitys and grabbing each primary_source (like a Post) and its Comments. Right now the primary_source is being eager-loaded, but the Comments are not; each loops hits the Comment table. This is a huge performance hit for me, which scales linearly with the number of Activitys I show.
How do I eager-load my Comments?
Assuming that all of your primary_sources are commentable,
…worked for me. To avoid hitting the database (and defeating the purpose of the includes) you’ll have to replace any references to root_comments with comment_threads (which do include child comments). This is because root_comments is actually defined in the gem (lib/acts_as_commentable_with_threading.rb) as a helper method:
Sources: The Rails Guide section on nested associations, along with peeking inside the acts_as_commentable_with_threading gem and a little trial and error in the console 🙂