Rails 7.1: best practices for `ActiveRecord::RecordNotFound` when using `includes` with custom conditions?
I'm stuck on something that should probably be simple... I'm dealing with I'm sure I'm missing something obvious here, but I'm stuck on something that should probably be simple... I'm working with an `ActiveRecord::RecordNotFound` behavior when trying to load associated records with `includes` in Rails 7.1. I have a `Post` model that belongs to a `User` model, and I'm trying to load the posts along with their users. The tricky part is I want to filter the users based on a specific condition (for instance, only users that are 'active'). Here's the code I'm using: ```ruby # In the PostsController @posts = Post.includes(:user).where(users: { active: true }) ``` However, Iโm getting this behavior: `ActiveRecord::RecordNotFound in PostsController#index`. Iโve verified that there are posts that match the condition but the associated users are not 'active'. I thought that using `includes` would prevent this behavior by eager loading the association, but it seems thatโs not the case when combined with conditions on the associated table. I've tried switching to a `joins` instead, but that returns an empty result set since it only fetches posts where the user matches. Iโm also aware of the `left_outer_joins`, but Iโm not sure how to implement that correctly in this case. Here's my current attempt at using `left_outer_joins`: ```ruby @posts = Post.left_outer_joins(:user).where(users: { active: true }) ``` This still results in an empty array. What am I missing here? How can I correctly fetch posts with their associated users while applying conditions to the users without running into a `RecordNotFound` behavior? Is there a better approach? I'm working on a microservice that needs to handle this. Any ideas how to fix this? I'd love to hear your thoughts on this. What are your experiences with this? Could someone point me to the right documentation?