我有两个模型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
正在执行的情况下。如何使用optimise
在view
和action
中进行此查询eagerloading
?
答案 0 :(得分:1)
由于视图中的以下行,您的查询会再次被调用:
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
documentation。
答案 1 :(得分:0)
将查询行更改为此。这将使用where子句急切加载您的所有in_outs
,以便您只运行一个查询。这样就可以使您的视图得到优化,并且不必在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)
{{1}}