计算过去7天内创建的记录

如何更改下面的查询以仅选择在过去7天内创建的记录?

self.favorites.count 

此function位于我的User模型中。

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

你可以像这样添加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 

我建议你为你的模型添加一个范围:

 class User < ActiveRecord::Base scope :recents, where("created_at > ?", Time.now-7.days) end 

那你可以做

 self.favorites.recents.count 

Rails 4+中

此代码似乎不起作用:

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

我尝试过:

 scope :recent, -> { where("DATE(created_at) > ?", (Date.today).to_time - 7.days) } 
 self.links.where("created_at > ?", Time.now-7.days).count