I have something like
<% @users.each do |u| %>
...
<% @interests.each do |i| %>
<% if i joins u in interests_users %> <-- That is not working that way! = Problem
...
<% i.id %>
...
<% end %>
<% end %>
...
<% end %>
I need to output each interest-id that joins users in interests_users for every user. But i cannot use a sql query for each user, because that would be too much for the server, so i query the whole interests table and want to filter it in the view.
Anyone got a simple solution for that?
You’re thinking about this too view-centric – this is a data issue, so the model(s) should take care of it.
I’m guessing you have an n-m relationship between users and interests, with the interests-users join table in the middle. The models should define that relationship something like this:
This is with has_and_belongs_to_many (HABTM). The models then already take care of “selecting” which interests are “on” each user, simply query them with user_instance.interests, i.e. do
If that generates a query for interests for each user, you can eager load the data when getting the users:
Edit:
Oh yeah and if you want to list all interests and mark those a user has associated, something like this should work: