I have a Booking
model , associated with Availability
> Facility
> Venue
I have a page in my view which renders all bookings
for a given venue
and it's causing a huge N+1 query.
Controller Action:
def summary
@venue = Venue.find params[:venue_id]
@bookings = Booking.includes{availability.facility.venue}.for_venue(@venue).references(:all).sort_recent
end
View:
<table id="booking-history" class="table table-condensed table-hover">
<thead>
<th>Date</th>
<th>Time</th>
<th>Facility</th>
<th>Purchase Time</th>
<th>User</th>
<th>Price</th>
<th>Receipt</th>
</thead>
<tbody>
<!-- venue_bookings is a method in venues helper -->
<%= render :partial => "bookings/booking", collection: bookings, as: :booking %>
</tbody>
</table>
Partial:
<tr>
<!-- avail date -->
<td><%= booking.availability.start_time.strftime("%a, %b %d %Y")%></td>
<!-- avail time -->
<td><%= booking.availability.start_time.strftime("%I:%M")%> - <%= booking.availability.end_time.strftime("%I:%M %p")%></td>
<td><%= booking.facility.name %></td>
<td><%= booking.created_at.to_formatted_s(:short) %></td>
<td><%= User.find(booking.user_id).name %></td>
<td><%= number_to_currency booking.total_price%></td>
<!-- Receipt Link -->
<td> <%= link_to("Receipt", charge_path(booking) ) %></td>
</tr>
Bullet Log:
user: vagrant
N+1 Query detected
Booking => [:facility]
Add to your finder: :includes => [:facility]
N+1 Query method call stack
/vagrant/playtoday/app/views/bookings/_booking.html.erb:6:in `_app_views_bookings__booking_html_erb___965508066735177428_69970894883840'
/vagrant/playtoday/app/views/bookings/_bookingHistory.html.erb:21:in `_app_views_bookings__booking_istory_html_erb___724060916350777358_69971212148620'
I already have includes in the class variable, I'm not sure where else I should be doing it.