Home > Blockchain >  group_by_month(:date).select() not giving date value in the desired output
group_by_month(:date).select() not giving date value in the desired output

Time:07-08

I am using the following code to group my active record relation by month. But as I extract attributes, I do not know how to get the date value as well.

This is my code:

books.group_by_month(:date).select("COUNT(*) as total, SUM(first_attribute) as fa").as_json

The output for the same is:

[
  {"total"=>273, "fb"=>2864977652, "id"=>nil}, 
  {"total"=>370, "fb"=>3882834096, "id"=>nil}, 
  {"total"=>37, "fb"=>300460723, "id"=>nil}
]

How will I know which hash is for which month, how can I include the month data in my query as well?

CodePudding user response:

Try this code

books.select("COUNT(*) as total, SUM(first_attribute) as fa").group_by { |record| record.date.strftime('%m') } 

CodePudding user response:

If not to use method group_by_month from groupdate gem you can do it this way:

books.select(
  "COUNT(*) AS total, SUM(first_attribute) AS fa, to_char(date, 'YYYY-MM') AS month"
).group(:month)

# output

[
  {"total"=>273, "fb"=>2864977652, "month" => "2022-06", "id"=>nil}, 
  {"total"=>370, "fb"=>3882834096, "month" => "2022-05", "id"=>nil}, 
  {"total"=>37, "fb"=>300460723, "month" => "2021-06", "id"=>nil}
]
  • Related