Rails activerecord: query for record by a datetime field?
I'm trying to query for records in the TimeSlot
table by the field start_date which has type datetime
开发者_开发百科. Here's what I've tried so far that's failed:
TimeSlot.where(:start_date => DateTime.new(2010, 9, 1))
TimeSlot.where(:start_date => DateTime.new(2010, 9, 1).to_s)
TimeSlot.where(:start_date => "2010-09-08")
TimeSlot.where(:start_date => "2010-09-08 00:00:00")
I'd appreciate any help.
Your queries look good to me.
Are you sure that you have a matching row in the db?
To debug, look in your logs/development.log file.
Added:
Problem could be timezones. Your query is using your server's timezone. Your data could be stored in a different timezone.
I'm betting it is a timezone thing as well. Everything in the DB is automatically converted to UTC by rails. Queries 1 and 4 should work if there isn't an offset.
Answer from rubyonrails.org
Client.where("created_at >= :start_date AND created_at <= :end_date", {:start_date => params[:start_date], :end_date => params[:end_date]})
or
Client.where("created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date))
Here is what I have for query all the TimeSlot start at "2010-09-08", if your start_date is a date field.
TimeSlot.where("start_date >= ? AND start_date <= ?", "2010-09-08", "2010-09-08")
If you start_date is a datetime field.
TimeSlot.where("start_date >= ? AND start_date <= ?", "2010-09-08", "2010-09-09")
Because the datetime start at 00:00:00
精彩评论