Rails 3 Comparing DateTime with date in ActiveRecord request

I am trying to find a model for any dates equal to a specific date, without specifying a timestamp. In Rails, I could just do it like DateTime.to_date == somedate , however I don't think it is quite easy to formulate it in SQL, where I could not apply the to_date method to the whole column, for example created_at:

 Foo.where("created_at == some_day_without_time_stamp").count 

Initially, I thought that since I used the postgresql database, I could just use the psql syntax, but I really prefer to leave it in ActiveRecord to decide which sql is most applicable and keep my code agnostic with the database providers. Is this possible without any additional plugins or gems?

+7
source share
4 answers

Try created_at >= some_day_with_00:00:00 timestamp and create_at < some_day_plus_one_with_00:00:00 timestamp

+4
source

I would do something like ...

 someday = Date.today Foo.where( :created_at => (someday)..(someday + 1.day) ) 

This captures all created_at dates between midnight on someday and someday + 1 . This is included (so it will include Foo, created at midnight +1 day), but can be “good enough” for your needs without falling into timestamps.

For convenience, I would wrap it as scope

 scope :on_day, ( lambda do |someday| where( :created_at => (someday)..(someday + 1.day) ) end ) 

So,

 Foo.on_day( Date.yesterday ).count 

well read.

+9
source

The DateTime class has two useful methods: beginning_of_day and end_of_day .

In this case, when you have a Date object, you can:

 Foo.where('created_at >= #{Date.today.to_time.beginning_of_day} AND created_at <= #{Date.today.to_time.end_of_day}') 

Note that you need to convert the Date object to a DateTime object

+9
source

With scope:

 scope :on_day, (lambda do |day| where(date: day.beginning_of_day..day.end_of_day) end) 

Using:

 Foo.on_day(Date.today).count 
+7
source

All Articles