我无法在 24 小时内获取与用户相关的特定对象的所有展示次数总和。基本上,我想计算 current_user 帖子的每日展示次数。
我尝试了六七种不同的方法,但都没有奏效。我最新的是下面那个。
def posts_daily_impressions_count(current_user)
current_user.posts.sum(&:impressionist_count).group_by_day(:created_at)
end
我无法在 24 小时内获取与用户相关的特定对象的所有展示次数总和。基本上,我想计算 current_user 帖子的每日展示次数。
我尝试了六七种不同的方法,但都没有奏效。我最新的是下面那个。
def posts_daily_impressions_count(current_user)
current_user.posts.sum(&:impressionist_count).group_by_day(:created_at)
end
您可以通过仅跟踪在日/月/年内创建的帖子来解决此问题。
为帖子创建范围
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)}
在 sum 方法之前应用它们
<%= current_user.posts.today.sum(&:impressionist_count) %>
这将为您提供在您关注的时间范围内创建的印象。
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')]
结果将是这样的数组:-
=> [#<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>]
并且您可以在数组结果的每个单独元素上调用别名列名,如下所示:-
posts_daily_impressions_count[0].total_impressions
=> 8