统计最近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  

您可以像这样添加where条件:

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

In 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

如果你在Rails中工作,你可以只使用ago datetime方法,而不是做奇怪的时间数学。

scope :recent, -> { where("created_at > ?", 1.week.ago) }

在Rails中,你通常可以避免许多复杂的数据准备和类型转换,而这些在其他语言/框架中可能不得不做。

回复:原来的帖子,我可能会这样重构它:

# Using association extensions here to filter this down,
# the ellipses parenthetical should be whatever you're using for your
# association definition.
has_many :links ( ... ) do
  def since(last_date)
    where('created_at > ?', last_date)
  end
end
has_many :favorites (...) do
  def since(last_date)
    where('created_at > ?', last_date)
  end
end
# Don't use magic numbers; codify them for context.
LINK_SCORE_MULTIPLIER = 5
FAVE_SCORE_MULTIPLIER = 0.5
# Note this does not persist it in the database; if you want it to persist 
# you'll want to execute an update instead. However it does memoize it so multiple
# calls will pull from the in-memory cache of the object instead of re-querying it
def score(recalculate: true)
  @score ||= (links.since(1.week.ago).count * LINK_SCORE_MULTIPLIER) +
            (favorites.since(1.week.ago).count * FAVE_SCORE_MULTIPLIER)
end

那么你就被动地引用它:

@user.score # runs the query and saves to memory
@user.score # pulls from memory
@user.score(recalculate: true) # re-runs the query and saves to memory
@user.save  # persists the result (assuming you have a field for :score)

这可能需要重构,但根据您的数据建模方式,您可能能够使用counter_cache来跟踪它(这将需要has_many, through关联,并且counter_cache将在连接模型上。

我正在寻找可以返回last 7 days的记录,即不包括今天。但这对我有用,它可以为last n days工作。

last_n_days = 7
Model.where('created_at BETWEEN ? AND ?', Date.today-last_n_days, Date.today-1).count
与范围

scope :last_n_days, lambda {|n| where('created_at BETWEEN ? AND ?', Date.today - n, Date.today - 1)}

最新更新