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

时间:2011-12-08 05:52:56

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

如何更改下面的查询以仅选择过去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  

6 个答案:

答案 0 :(得分:46)

您可以添加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  

答案 1 :(得分:10)

我建议您为模型添加范围:

class User < ActiveRecord::Base

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

end

然后你可以做

self.favorites.recents.count

答案 2 :(得分:7)

Rails 4 +

此代码似乎无效:

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

我试过了:

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

答案 3 :(得分:1)

self.links.where("created_at > ?", Time.now-7.days).count

答案 4 :(得分:0)

如果您在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_manythrough关联,并且counter_cache将在加入模型上。

答案 5 :(得分:0)

我一直在寻找可以返回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)}