簡體   English   中英

最好的查詢方式是什么?

[英]what is the best way to query?

我有兩個模型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正在再次執行。 如何通過使用eagerloading使此查詢在viewaction 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM