Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find records from today, yesterday and so on with Ruby on Rails?

I want to find all records, say Posts, created today with Ruby on Rails, then all Posts created yesterday, and so on… how should I do?

Thank you,

Kevin

like image 509
martini-bonanza Avatar asked Dec 01 '22 05:12

martini-bonanza


1 Answers

Try this:

#Today
Posts.find(:all, conditions: { :created_at => Date.today...Date.today + 1 })
#Yesterday
Posts.find(:all, conditions: { :created_at => Date.today - 1...Date.today })

Or this (preferable, in my opinion):

#Today
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today] )
#Yesterday
Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today - 1] )
like image 63
Daniel O'Hara Avatar answered Dec 04 '22 04:12

Daniel O'Hara