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

Dru*_*Dru 23 ruby activerecord ruby-on-rails ruby-on-rails-3

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

self.favorites.count
Run Code Online (Sandbox Code Playgroud)

此功能位于我的User模型中.

 def calculate_user_score
    unless self.new_record?
      self.score = (self.links.count * 5) + (self.favorites.count * 0.5)
    end
  end  
Run Code Online (Sandbox Code Playgroud)

Ben*_*Lee 46

你可以where像这样添加一个条件:

self.favorites.where('created_at >= ?', 1.week.ago).count
Run Code Online (Sandbox Code Playgroud)

对于您的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  
Run Code Online (Sandbox Code Playgroud)


Aug*_*ger 12

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

class User < ActiveRecord::Base

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

end
Run Code Online (Sandbox Code Playgroud)

那你可以做

self.favorites.recents.count
Run Code Online (Sandbox Code Playgroud)


ald*_*n.h 7

Rails 4+中

此代码似乎不起作用:

"created_at > ?", Time.now-7.days
Run Code Online (Sandbox Code Playgroud)

我尝试过:

scope :recent, -> { where("DATE(created_at) > ?", (Date.today).to_time - 7.days) }
Run Code Online (Sandbox Code Playgroud)