Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count records created within the last 7 days

Tags:

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   
like image 453
Dru Avatar asked Dec 08 '11 05:12

Dru


2 Answers

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   
like image 100
Ben Lee Avatar answered Oct 13 '22 05:10

Ben Lee


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 
like image 20
Augustin Riedinger Avatar answered Oct 13 '22 03:10

Augustin Riedinger