Searching by datetime field with Rails


#1

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.


#2

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”.