Reputation: 2222
I'm writing a scope to group PageView
's by created_at date and then retrieving the count for each date. Here is my scope:
scope :count_by_date, -> { group('date(created_at)').count }
This returns the counts in this format:
{Wed, 26 Aug 2020=>3, Tue, 25 Aug 2020=>8}
I'm then using this data with Chart.js to create various charts in my app. The issue I'm having is I need the hash returned from the scope to be in this format so I can use the keys and values as the charts x and y values:
{"2020-08-26"=>3, "2020-08-25"=>8}
How can I get the data back in the format I need?
Upvotes: 0
Views: 142
Reputation: 1407
Try the below:
Define the scope with custom select
scope :count_by_date, -> {
group('DATE(created_at)')
.pluck('DATE(created_at)::varchar', 'COUNT(*)')
}
The above scope will return two dimension array like the below:
[["2020-08-11", 1], ["2020-08-24", 5], ["2020-08-14", 1]]
You need to convert the array data into hash after querying with to_h
MyModel.count_by_date.to_h
Upvotes: 2