How can I alter the query below to only select records created within the last 7 days?
self.favorites.count
This function is located in my User
model.
def calculate_user_score unless self.new_record? self.score = (self.links.count * 5) + (self.favorites.count * 0.5) end end
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With