How to prevent N+1 query implementing includes in Rails 6 when using polymorphic associations?
I'm experimenting with I'm working on a Rails 6 application where I'm using polymorphic associations to connect different models like `Comment` and `Post`..... I noticed that when I try to fetch comments along with their associated posts, I'm working with an N+1 query scenario. Hereβs what my models look like: ```ruby class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Post < ApplicationRecord has_many :comments, as: :commentable end class Photo < ApplicationRecord has_many :comments, as: :commentable end ``` I attempted to load comments with their associated posts in my controller like this: ```ruby @comments = Comment.where(commentable_type: 'Post').includes(:commentable) ``` However, when I iterate through `@comments` in my view to display the post titles, I still notice a important increase in database queries: ```erb <% @comments.each do |comment| %> <p><%= comment.body %> - <%= comment.commentable.title %></p> <% end %> ``` I expected that using `.includes` would prevent the N+1 queries, but it seems like Rails is still running a separate query for each comment's `commentable`. I've also checked the logs, and I see multiple `SELECT` statements for fetching the posts. What am I missing here? Is there a better way to handle this kind of query with polymorphic associations to avoid N+1 issues? I'd love to hear your thoughts on this. I'm working on a microservice that needs to handle this.