简体   繁体   中英

what is the best way to query?

i am having two models employee and in_outs . the association between these are employee has many in_outs and in_out belongs to employee .i want to display the attendance of all the employees . For this my current logic is this.

logic in controller action:

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

and in view :

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

in this case in my view again queries are executing. how to make this query optimise in view and in action by using eagerloading ?

change you query line to this. This will eager load all your in_outs with the where clause so that you just run one query.This will make it so your view is optimized as well in won't have to run N+1 queries in each time each time you request an 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)

Your query is being called again due to the following line in your view: punch_record.employee.name .

In order to eager load employee you'll need to modify your query to be like so:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM