我有Booking
模型,与Availability
>相关联Facility
> Venue
我的视图中有一个页面,它为给定的bookings
呈现所有venue
,并且它会导致巨大的N + 1查询。
控制器操作:
def summary
@venue = Venue.find params[:venue_id]
@bookings = Booking.includes{availability.facility.venue}.for_venue(@venue).references(:all).sort_recent
end
查看:
<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>
部分:
<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>
子弹日志:
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'
我已经在类变量中包含了,我不确定我应该在哪里做它。