Count records created within the last 7 days
I recommend you add a scope to your model:
class User < ActiveRecord::Base
scope :recents, where("created_at > ?", Time.now-7.days)
end
Then you can do
self.favorites.recents.count
self.links.where("created_at > ?", Time.now-7.days).count
You can add a where
-condition like this:
self.favorites.where('created_at >= ?', 1.week.ago).count
And for your calculate_user_score
method, you probably want to do that for links
as well:
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
In Rails 4+
This code seems not working:
"created_at > ?", Time.now-7.days
I tried like:
scope :recent, -> { where("DATE(created_at) > ?", (Date.today).to_time - 7.days) }