计算过去 7 天内在 rails 中创建的用户数?[在计数语法方面需要帮助]



我看到了过去 7 天内创建的 Count 记录,但仍然需要一些帮助来正确使用 COUNT 的语法,现在我有

@count_users = User.count('comment')
这给了我所有评论的计数

,但我需要知道仅在过去 7 天或过去 1 个月内发表的所有评论的计数,但我无法找出正确的语法

这个计数:

@count_users = User.count('comment')

生成以下 SQL:

SELECT COUNT(comment) FROM "users"

因此,除非您的用户表中有注释列,否则它不会计算正确的对象

如果您有评论模型,则可以使用以下方法统计过去 7 天内创建的所有评论:

Comment.where('created_at >= ?', Time.zone.now - 7.days).count # count for a week
Comment.where('created_at >= ?', Time.zone.now - 1.months).count # count for a month

如果要计算特定用户的评论,可以使用以下命令(假设用户belongs_to评论和用户has_many评论):

Comment.where(user_id: user.i).where('created_at >= ?', Time.zone.now - 7.days).count

最新更新