什么是查询的最佳方式?

时间:2016-10-24 15:10:16

标签: mysql ruby-on-rails query-optimization has-many belongs-to

我有两个模型employeein_outs。这些关联是employee has many in_outsin_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正在执行的情况下。如何使用optimiseviewaction中进行此查询eagerloading

2 个答案:

答案 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}}