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

I want to find all the entries, for example, the messages created today with Ruby on Rails, and then all the messages created yesterday, etc. .... how can I do this?

Thanks,

Kevin

+4
source share
2 answers

Try the following:

#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 (preferred in my opinion):

 #Today Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today] ) #Yesterday Posts.find(:all, conditions: ["DATE(created_at) = ?", Date.today - 1] ) 
+15
source

As a rule, I save all dates on my server in the UTC time zone and allow the user interface to handle any change in the time zone. To get the request that you need in order to work correctly, I had to massage the incoming date. First, specify a specific UTC time interval.

 require 'date' class Post < ActiveRecord::Base def self.created(a_date) return Post.where(created_at: to_timerange(a_date)) end private def self.to_timerange(a_date) raise ArgumentError, "expected 'a_date' to be a Date" unless a_date.is_a? Date dts = Time.new(a_date.year, a_date.month, a_date.day, 0, 0, 0).utc dte = dts + (24 * 60 * 60) - 1 return (dts...dte) end end 

Then you can call

 # today posts = Post.created(Date.today) # yesterday posts = Post.created(Date.today - 1) 
+1
source

All Articles