Rails 7.1: How to prevent N+1 queries when eager loading polymorphic associations?
I'm getting frustrated with I'm building a feature where I tried several approaches but none seem to work... I'm working on a Rails 7.1 application where I have a polymorphic association set up for comments. Each comment can belong to either a post or an image, and I'm trying to eagerly load the associated records to avoid N+1 query issues. However, despite using `includes`, I'm noticing that there are still multiple queries being executed when I access the comments. Here's a simplified version of my models: ```ruby class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Post < ApplicationRecord has_many :comments, as: :commentable end class Image < ApplicationRecord has_many :comments, as: :commentable end ``` When I fetch a post along with its comments, I am doing this: ```ruby post = Post.includes(:comments).find(params[:id]) ``` Then I access the comments in the view like this: ```erb <% post.comments.each do |comment| %> <div><%= comment.body %></div> <% end %> ``` Even though I included comments in the query, I see multiple queries in the logs: ``` Comment Load (3.0ms) SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = $1 AND "comments"."commentable_type" = $2 ``` I've also tried using `joins` instead of `includes`, but that doesn't seem to suit my needs since I want to include comments even if there are none. I'm stumped as to why this is still happening. Is there something I'm missing in my eager loading? Additionally, I have double-checked that the foreign keys and types are set correctly in the database. Any insights on how to properly eager load polymorphic associations in this context would be greatly appreciated! This is for a REST API running on Debian. Am I approaching this the right way? This is happening in both development and production on macOS. Am I approaching this the right way?