Sylar Sylar - 2 months ago 7
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 => {...}, {...}
etc

"Monday" would be ruby's date format.

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

Controller:

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

def daily_sales(created=nil)
sales_by_date = Hash.new(0)

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
end

return sales_by_date
end


For views:

daily_sales(1.week.ago.to_datetime)


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

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