我看到了这个Count records created within the last 7 days但仍然需要一些帮助来正确理解 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
如果您想计算特定用户的评论,可以使用此方法(假设评论属于_用户并且用户有_许多评论):
Comment.where(user_id: user.i).where('created_at >= ?', Time.zone.now - 7.days).count
关于ruby-on-rails - 统计过去 7 天内在 Rails 中创建的用户数量? [需要 Count 语法帮助],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627383/