GreenTriangle
GreenTriangle

Reputation: 2460

How can I request only DB records created within the last day?

The table does have the default created_at and updated_at columns. I've Googled this problem, but can't seem to work it out. I want to say something like Review.where(created_at > Time.now - 24 hours) or something like that. What's the simplest/smartest way to do that?

Upvotes: 0

Views: 74

Answers (4)

sat's
sat's

Reputation: 323

Change your query to

Review.where('created_at > ?', Time.now - 24.hours)

This will return Reviews created in last 24 hours

Upvotes: 0

Pramod Shinde
Pramod Shinde

Reputation: 1892

Indeed more elegant way in Rails 3

Review.where('created_at > ? ', Time.now - 1.day) #compares date and time as well 
Review.where('created_at > ? ', Date.today - 1) #compares only date

Upvotes: 0

Pavan
Pavan

Reputation: 33542

To get all records that are created yesterday,you can do like this

Review.find(:all, :conditions => ["DATE(created_at) = ?", Date.today-1])

OR

Review.where("DATE(created_at) = DATE(?)", Date.today - 1)

Upvotes: 2

Bharat soni
Bharat soni

Reputation: 2786

The following will help you for your problem

rails 2

YourModelName.all :conditions => ["DATE(created_at) = DATE(?)", DateTime.now - 1]

rails 3

YourModelName.where("DATE(created_at) = DATE(?)", DateTime.now - 1)

Upvotes: 0

Related Questions