yellowreign
yellowreign

Reputation: 3638

Rails Show Subtotal by Date

I'm using mySQL for my Rails 4 app and I have a Sale model that has the fields sale_date, amount, and user_id.

What I'm trying to do is show the total amount per sale date.

<% @sales.each do |sale| %>      
   <%= sale.sale_date.strftime("%m/%d/%Y") %>
   <%= number_to_currency(sale.amount) %>
<% end %>

Currently, my controller only has this (which obviously doesn't subtotal):

@sales = @user.sales

How can I show sales subtotaled by date? Thank you!

Upvotes: 0

Views: 120

Answers (3)

dp7
dp7

Reputation: 6749

Try this:

<% @sales.group_by(&:sale_date).each do |sale| %>      
   <%= sale[0].strftime("%m/%d/%Y") %>
   <%= number_to_currency(sale[1].sum(&:amount)) %>
<% end %>

Upvotes: 0

Stanislav Gospodinov
Stanislav Gospodinov

Reputation: 36

If you are not familiar with scopes in rails I recommend you to read this.

A possible solution to your problem is to add the following scope to your Sales model.

scope :amount_per_sale, -> { group(:sale_date).sum(:amount) }

This scope will produse hash which contains the dates of a sale as keys and the amount as values. If you want to use this scope in combination with user instance it's very easy too.

@user.sales.amount_per_sale

Upvotes: 1

Hieu Pham
Hieu Pham

Reputation: 6707

My first thought, if there are not too many @sales, we can use ruby group_by method to group by sale_date. Ideally, it would be:

<% sales_group = @sales.to_a.group_by{ |sale| sale.sale_date.strftime("%m/%d/%Y") } %>
<% @sales_group.each do |sale_group| %>      
   <%= sale_group.first.sale_date.strftime("%m/%d/%Y") %>
   <%= number_to_currency(sale_group.sum(&:amount)) %>
<% end %>

You can move the logic of sales_group to controller & if there is a lot of @sales records, you may use database query instead of ruby.

This is a good reference https://stackoverflow.com/a/4061462/1789479

Upvotes: 0

Related Questions