Question

I am working on an application that helps a local restaurant track the hours worked each day. The user enters data through a model called a "Checkout" at the end of each shift. They select an employee that is associated with a has_many :through => employment, where the employment model is a join table. Granted, Checkout is a confusing term, but that is the DSL that the restaurant wanted to use.

How do you group the hours worked by each employee on a given day? There might be 2 checkouts in the database for that employee on that day – one from lunch and one from dinner.

I want to create a list of hours that each employee worked on a given day when their hours from that day might be stored in separate checkouts in the database.

Today's Date
Joe Employee
Hours worked: 12

Jill Employee
Hours worked: 4

etc.

How do I group the checkouts by employee when they are not an attribute on the checkouts model, but rather are an association through my employment model? Essentially, I'm trying to do something like this in my reports helper:

def checkouts_today
  current_user.checkouts.where( :date => Date.today )
end

def employee_hours_today
  checkouts_today.where( :employment => Employee.find_by(id: params[:id]) ).sum(:hours)
end

But I can't get it to work with the has_many :through association. I can only figure out how to total all hours from that day, not the total hours per employee.

Here are the relevant files:

Update: I can loop through each employee and display their checkouts with this:

<% @employees.each do |employee| %>
    <% if employee.checkouts.present? %>
        <p><%= employee.full_name %></p>

        <% employee.checkouts.each do |checkout| %>
            <%= checkout.date %>
            <%= checkout.shift %>
            <%= checkout.hours %>
        <% end %>
    <% end %>
<% end %>

But, I can't figure out how to sum their hours and display and return it in one block. It returns each checkout for each day under each employee's name. It also seems like this kind of logic should not be in the view.

Was it helpful?

Solution

1st method

in checkout.rb:

scope :checkouts_today, -> {where(date: Date.today)}

in your view or controller:

employee.checkouts.checkouts_today.sum(:hours)

2nd method

in employee.rb

has_many :today_checkouts, class_name: "Checkout", conditions: {date: Date.today}

in your view or controller:

employee.today_checkouts.sum(:hours)

Not sure the 2nd way would work as you have a join table to get the relation between Employee and Checkout. As we discussed in chat, you can drop the join table, in your case I don't see where you'll need it, give your app more space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top