Rails 7: How to correctly implement polymorphic associations with eager loading to avoid N+1 queries?
I've been working on this all day and I'm working on a personal project and I'm working on a Ruby on Rails 7 application and I'm working with an scenario with polymorphic associations... I've set up a `Comment` model that can belong to either a `Post` or a `Video` through a polymorphic association. However, when I try to fetch comments along with their associated posts or videos, I notice an N+1 query question that severely affects performance. Here's how my models are set up: ```ruby class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true end class Post < ApplicationRecord has_many :comments, as: :commentable end class Video < ApplicationRecord has_many :comments, as: :commentable end ``` When I try to load comments for a specific post and include the associated comments, I use the following code: ```ruby post = Post.includes(:comments).find(post_id) ``` However, when I check the logs, I see that Rails is still generating separate queries for loading each comment's associated `commentable` record, resulting in multiple queries like so: ``` SELECT "comments".* FROM "comments" WHERE "comments"."commentable_type" = 'Post' AND "comments"."commentable_id" = ? SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? SELECT "videos".* FROM "videos" WHERE "videos"."id" = ? ``` I've tried using `includes` and `joins`, but it doesn't seem to resolve the scenario. I also considered using `preload`, but that didn't seem to help either. I'm looking for a way to effectively eager load the comments along with their polymorphic associations to avoid the N+1 query question. Is there something I'm missing in my setup or usage? Any best practices or suggestions would be greatly appreciated! What's the best practice here? This is happening in both development and production on Ubuntu 22.04. I'd love to hear your thoughts on this. I'm coming from a different tech stack and learning Ruby. Thanks for your help in advance!