[英]what is the best way to query?
我有兩個模型employee
和in_outs
。 這之間的關聯是employee
has many
in_outs
和in_out
belongs to
employee
。我想要顯示的attendance
所有的employees
。 為此,我current logic
是這樣。
控制器動作中的邏輯:
def view_all_employee_attendance
employees = Employee.all
@all_employess_punch_in_outs = []
employees.each do |employee|
@all_employess_punch_in_outs << employee.in_outs.where('date >= ? and date <= ?', Date.today.at_beginning_of_month, Date.today)
end
end
並且鑒於:
<tbody>
<% @all_employess_punch_in_outs.each do |punch_record| %>
<tr>
<td><%= punch_record.employee.name %></td>
<td><%= punch_record.check_in %></td>
<td><%= punch_record.check_out %></td>
</tr>
<% end %>
</tbody>
在這種情況下,我view
queries
正在再次執行。 如何通過使用eagerloading
使此查詢在view
和action
optimise
?
將您的查詢行更改為此。 這將貪婪加載所有in_outs
與where子句讓你只運行一個query.This將使它所以你的觀點進行了優化,以及將不用跑了N+1
,每次在每次請求的時候查詢in_out
employees = Employee.joins(:in_outs).all.where('in_outs.date >= ? and in_outs.date <= ?', Date.today.at_beginning_of_month, Date.today).preload(:in_outs)
由於視圖中的以下行,您的查詢被再次調用: punch_record.employee.name
。
為了渴望加載employee
您需要將查詢修改為:
def view_all_employee_attendence
@employee_in_outs = Employee.all.includes(:in_outs).where('in_outs.date >= ? and in_outs.date <= ?', Date.today.at_beginning_of_month, Date.today)
end
includes
文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.