I have a relationship table for users and related users.
If I do @user.related_users I get a list of user_id that point to the users.
On my view I want to list their names with
<% current_user.related_users.each do |u| %>
<%= User.find(u).name %>
<% end %>
I worry that it might overload the DB too much, since it fetches every related_user from the DB every time someone access that view.
Is there a better way of doing this? or that is the way and there’s nothing I can do about it?
That’s what eager loading is for. Ideally, in your model,
related_usersshould be an association:Then in your controller, fetch the
@userlike this:That will perform only 1 query for all related users, instead of one query for each related user (a so-called 1+N problem).
Or, if you don’t want to rewrite your model code, simply load all related users into a variable in your controller:
and iterate over that in your view. This will fetch all related users with a single query with a
WHERE id IN (...)clause.