Forum: Ruby on Rails Searching by datetime field with Rails

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Marston A. (Guest)
on 2006-04-21 17:03
What would be the best way to search a MySQL datetime field with rails?

I have an table in a db which will have many rows, I primarily search it
by date.  I have a datetime column named simply "datetime", of course
along with the date it keeps the time info.

I do need the time info, however I only need to search the rows via the
dates, so what would be the easiest way to search via active record?

For example say I have a datetime that says:

2006-04-21 12:00:00

but only need to search

2006-04-21

Or should I keep separate date and time columns in the database?

Thanks for any help.
Bryan D. (Guest)
on 2006-04-21 18:20
It isn't pretty, but the way to do it is:

@widgets = Widget.find(:all, :conditions => "DATE(datetime) =
#{search_date}")

where search_date is the date that you want to find rows on. The DATE
mysql function casts a datetime into a date object, so it can be
equivalent to your search date.

Another way to do it would be to search for widgets that have a datetime
between "search_date 0:00" and "search_date 23:59", that is, making two
dates that would enclose any datetime falling into a given "day".
This topic is locked and can not be replied to.