1

두 모델 employeein_outs이 있습니다. 이들 사이의 연관은 employeesattendance을 표시하려고합니다.이 둘 사이의 연관은 employeehas manyin_outsin_out 입니다. 이것을 위해 내 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 

및 뷰

view 다시 queries가 실행되고이 경우

 <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> 

. 이 쿼리를 만드는 방법 을 사용하여 viewactionoptimise?

+0

질문에 몇 가지 코드 서식 문제가 있습니다. – meshpi

답변

0

변경하면이 줄이 있습니다. 이렇게하면 모든 in_outs에 where 절이로드되므로 하나의 쿼리 만 실행하면됩니다. 이렇게하면보기가 최적화되어보기가 실행될 때마다 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) 
+0

날짜는'in_outs' 모델을 참조하므로 날짜에 접두어로'in_outs.date> =? '가 표시됩니다. – meshpi

+0

눈 감사합니다! –

+0

오류 : ActiveRecord :: StatementInvalid at/attendance/view_attendance Mysql2 :: 오류 : 'where 절'에서 'in_outs.date'알 수없는 열 : 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

Thanks @CdotStrifeVII 변경했습니다! – meshpi

+0

어리석은 질문 일지 모르지만 '모두'를 사용해야하는 이유는 무엇입니까? '(...). includes (: in_outs)'와 같은 효과가 없습니까? – jaydel

관련 문제