Reputation: 131
I am having trouble with getting the sum of all impressions for a specific object that relates to a user within a 24 hour span. Basically, I want to count the daily impressions for the current_user's posts.
I tried six or seven different approaches, but none work. My latest is the one below.
def posts_daily_impressions_count(current_user)
current_user.posts.sum(&:impressionist_count).group_by_day(:created_at)
end
Upvotes: 0
Views: 310
Reputation: 131
You can solve this problem by tracking only the posts created within the day/month/year.
Create the scopes for the posts
scope :today, -> {where("created_at >= ? AND created_at < ?", Time.now.beginning_of_day, Time.now.end_of_day)}
scope :yesterday, -> {where("created_at >= ? AND created_at < ?", 1.day.ago.beginning_of_day, 1.day.ago.end_of_day)}
scope :this_month, -> {where("created_at >= ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)}
Apply them before the sum method
<%= current_user.posts.today.sum(&:impressionist_count) %>
This will give you the impressions that were created within the span of time that you're focusing on.
Upvotes: 0
Reputation: 6531
posts_daily_impressions_count = Post.joins(:User).where('users.id = ? AND posts.created_at between ? and ?', current_user.id,Date.today.beginning_of_day, Date.today.end_of_day).select('sum(posts.impressionist_count) as total_impressions').group('posts.created_at')]
It will results as array like this:-
=> [#<Post:0x007f8ba416f300 id: nil>,
#<Post:0x007f8ba416f170 id: nil>,
#<Post:0x007f8ba416ef90 id: nil>,
#<Post:0x007f8ba416ee00 id: nil>,
#<Post:0x007f8ba416ec70 id: nil>,
#<Post:0x007f8ba416eae0 id: nil>,
#<Post:0x007f8ba416e950 id: nil>]
and you can call alias column name on each individual element of results of array like this:-
posts_daily_impressions_count[0].total_impressions
=> 8
Upvotes: 0