I need to query comments made in one day. The field is part of the standard timestamps, is created_at. The selected date is coming from a date_select. How can I use ActiveRecord to do that?
I need somthing like:
"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"
there are several ways. You can use this method:
Or this:
If you only want to get one day it would be easier this way:
Rails 5.1 introduced a new date helper method
all_day
, see: https://github.com/rails/rails/pull/24930If you are using Rails 5.1, the query would look like:
This code should work for you:
For more info have a look at Time calculations
Note: This code is deprecated. Use the code from the answer if you are using Rails 3.1/3.2
I have been using the 3 dots, instead of 2. Three dots gives you a range that is open at the beginning and closed at the end, so if you do 2 queries for subsequent ranges, you can't get the same row back in both.
And, yes, always nice to use a scope!
There should be a default active record behavior on this I reckon. Querying dates is hard, especially when timezones are involved.
Anyway, I use: