2016-10-24 256 views
1

我有兩個型號employeein_outs。這些之間的關聯是employeehas manyin_outsin_outbelongs toemployee。我想要顯示所有employeesattendance。爲此我的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正在執行。如何使用eagerloadingviewaction中查詢optimise

+0

你的問題有一些代碼格式問題。 – meshpi

回答

0

將您的查詢行更改爲此。這將使用where子句急切地加載所有的in_outs,這樣你就可以運行一個查詢。這將使得你的視圖得到優化,並且在每次你請求一個in_out

時,在每次不需要運行 N+1查詢
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) 
+0

日期指的是'in_outs'模型,所以你應該在'in_outs.date> =?前加上日期' – meshpi

+0

好的眼睛謝謝! –

+0

出現錯誤:ActiveRecord :: StatementInvalid at/attendance/view_attendance Mysql2 ::錯誤:未知列in_outs.date'where子句':SELECT'employees'。* FROM'employees' WHERE(in_outs.date> = '2016-10-01'和in_outs.date <='2016-10-24') – John

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 

includesdocumentation

+1

想你在這裏有一個錯字'include'應該是'includes' –

+0

謝謝@CdotStrifeVII我已經改變了! – meshpi

+0

可能是一個愚蠢的問題,但爲什麼使用'all'?不會'where(...)。includes(:in_outs)'具有相同的效果嗎? – jaydel

相關問題