2011-12-08 71 views
20

如何更改以下查詢以僅選擇最近7天內創建的記錄?在過去7天內創建的計數記錄

self.favorites.count 

此功能位於我的User模型中。

def calculate_user_score 
    unless self.new_record? 
     self.score = (self.links.count * 5) + (self.favorites.count * 0.5) 
    end 
    end 

回答

40

您可以添加where -condition這樣的:

self.favorites.where('created_at >= ?', 1.week.ago).count 

併爲您的calculate_user_score方法,你可能想要做的是爲links還有:

def calculate_user_score 
    unless new_record? 
    self.score = (links.where('created_at >= ?', 1.week.ago).count * 5) + 
     (favorites.where('created_at >= ?', 1.week.ago).count * 0.5) 
    end 
end 
1
self.links.where("created_at > ?", Time.now-7.days).count 
7

我建議你爲你的模型添加一個示波器:

class User < ActiveRecord::Base 

    scope :recents, where("created_at > ?", Time.now-7.days) 

end 

然後,你可以做

self.favorites.recents.count 
+0

起來很好的分離 –

4

的Rails 4+

此代碼似乎不工作:

"created_at > ?", Time.now-7.days 

我想這樣的:

scope :recent, -> { where("DATE(created_at) > ?", (Date.today).to_time - 7.days) } 
相關問題