2013-01-31 52 views
0

我看到這個Count records created within the last 7 days但仍需獲得的COUNT正確的語法一些幫助,現在我有計算過去7天內在rails中創建的用戶數? [需要幫助計數的語法]

@count_users = User.count('comment') 

這給我算的所有意見,但我需要知道算的只是在最近7天或最近1個月提出的所有意見,但我無法找出正確的語法爲它

+3

我假設你想使用'created_at'屬性來比較當前日期。 'User.where('created_at> =?',7.days.ago).count('comment')' – jvnill

回答

2

此計數:

@count_users = User.count('comment') 

生成以下SQL:

SELECT COUNT(comment) FROM "users" 

所以,除非你在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 
+0

評論實際上只是用戶表 – iCyborg

+0

中的一個字段所以看看@jvnill對你的答案的評論;) – MrYoshiji

+0

實際上你的代碼工作,令人驚訝的是它非常簡單:)謝謝 – iCyborg