简体   繁体   中英

How to count daily impressions for an object related to the current_user with Impressionist gem

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM