Eager loading associations related to user

Published: (April 6, 2026 at 03:40 PM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Why make this post

It was a problem I faced myself and couldn’t find a direct answer to: “How do I eager load if a user has liked a post? If a user is already friends with another user?”
I wanted to know how to eager load an association that is directly related to the user, and this post documents a solution that might help others with the same issue.

In this example we will eager load posts alongside the user’s like.

Current Attributes

To know if an Active Record object is related to a user, we first need to share some unique data related to the user with the model. This is done with CurrentAttributes.

# app/models/current.rb
class Current  { where(id: Current.user_id) },
           through: :likes,
           source: :user
end

The liked association will contain either one User record (the current user) or be empty; it will never be nil.

Usage in Controller and View

Controller

# app/controllers/posts_controller.rb
class PostsController 
  
    Liked
  
    Like
  

  

  

Conclusion

This is one way to handle eager loading of user‑specific associations in Rails. It can be adapted for other scenarios, such as checking friendships or other user‑related flags.

0 views
Back to Blog

Related posts

Read more »