advanced patterns when using `includes` with `joins` in Rails 6.1 causing duplicated records
I'm trying to figure out I'm migrating some code and I've searched everywhere and can't find a clear answer. I've been banging my head against this for hours. I'm working with an scenario in Rails 6.1 where using `includes` alongside `joins` is resulting in duplicated records. I have a `User` model that has many `Posts`, and I'm trying to fetch users along with their posts while applying some additional filtering on the `Posts`. My query looks like this: ```ruby User.includes(:posts).joins(:posts).where(posts: { published: true }).distinct ``` The intention is to get unique users who have published posts. However, when I inspect the resulting collection, it seems like I am getting multiple instances of the same `User`, once for each of their published posts. I've tried adding `.distinct` after the query, but it doesn't seem to help. I also tested ```ruby User.joins(:posts).where(posts: { published: true }).distinct ``` and that returns the unique users as expected, but I need the associated posts to be eager-loaded as well. I even considered changing to a subquery, but I still want to stick to this structure for performance reasons. The output of the first query looks like this: ``` User Load (2.4ms) SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "posts"."published" = true ``` When I iterate through the results, I see multiple entries for users with multiple published posts. What can I do to ensure I only get unique user records while also eager loading the associated posts properly? Any insights or alternative approaches would be greatly appreciated! This is part of a larger CLI tool I'm building. How would you solve this? For context: I'm using Ruby on macOS. Any ideas what could be causing this? I'm on Ubuntu 20.04 using the latest version of Ruby. Is there a simpler solution I'm overlooking? How would you solve this?