Sylar Sylar - 10 months ago 42
Ruby Question

Allocate daily sales to date created

Im trying to gather all sales made within a week and put each sale in day made. If Moday was two sales, then

Monday => {...}, {...}

"Monday" would be ruby's date format.

In my db I have 5 sale objects: Two sales on Monday and two on Tuesday.


def daily_customer_sale(created)
date_and_id = Sale.where('created_at >= ?', created).pluck(:created_at, :id)
date_and_id.each do |obj|
yield(obj.first, obj.last)

def daily_sales(created=nil)
sales_by_date =

daily_customer_sale(created) do |date, id|
s_date = date.to_date
sales_by_date[s_date] = Sale.find(id) # Seems to return only one object per day

return sales_by_date

For views:


What I get in two dates (correct) in which each data has only one object when it should be two or more per date. Is there something wrong?

Answer Source

You don't need complex logic to do it. Here is a cleaner way

Sale.where('created_at >= ?', created_at).group_by{ |sale| sale.created_at.to_date}

It will return All the sales grouped by day. key will be date object and for each day there will be sale array containing all of the sales for that day.

If you need string based key you can format it as you like as per below

Sale.where('created_at >= ?', created_at).group_by{ |sale| sale.created_at.to_date.to_s } #default date format

Sale.where('created_at >= ?', created_at).group_by{ |sale| sale.created_at.to_date.strftime("%d/%m/%Y") } #23/09/2016

You can have a look at Group by method