Dru Dru - 7 months ago 9
Ruby Question

Count records created within the last 7 days

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

Answer

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  
Comments