Reputation: 607
I need a little advice about the join
and includes
methods.
I display a list of groups in the index view. Each has a modal associated, and, in this modal, I would like to display the requests associated to this group. Normally, I'd use @requests = group.requests
, but would like to use join
for sending just one request to my database.
Since I'm in the index view, I don't have a @
group in my action.
controller:
def index
@groups = current_user.groups
end
view (index):
<% @groups.each do |g| %>
<MODAL>
<% @requests = g.requests %>
<% @requests.each do |r| %>
<%= r.date %>
<% end %>
</MODAL>
<% end %>
I guess I can also use join
and include
for @groups
, but there is already one SQL request, so I'm good with it.
Upvotes: 0
Views: 66
Reputation: 1656
In your controller, add includes like this to preload requests and avoid n+1 queries.
def index
@groups = current_user.groups.includes(:requests)
end
View is fine, but you can also write as:-
<% @groups.each do |g| %>
<MODAL>
<% g.requests.each do |r| %>
<%= r.date %>
<% end %>
</MODAL>
<% end %>
Upvotes: 2