如何更改下面的查询以仅选择过去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
答案 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_many
,through
关联,并且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)}