【问题标题】:Rails activerecord: query for record by a datetime field?Rails activerecord:按日期时间字段查询记录?
【发布时间】:2010-08-24 22:20:56
【问题描述】:
我正在尝试通过类型为datetime 的字段start_date 查询TimeSlot 表中的记录。这是我迄今为止尝试过的失败:
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")
我将不胜感激。
【问题讨论】:
标签:
ruby-on-rails
activerecord
ruby-on-rails-3
【解决方案1】:
您的查询对我来说看起来不错。
您确定在 db 中有匹配的行吗?
要调试,请查看您的 logs/development.log 文件。
添加:
问题可能是时区。您的查询正在使用您的服务器的时区。您的数据可以存储在不同的时区。
【解决方案2】:
我打赌这也是一个时区问题。数据库中的所有内容都会通过 rails 自动转换为 UTC。如果没有偏移量,查询 1 和 4 应该可以工作。
【解决方案3】:
来自 rubyonrails.org 的回答
Client.where("created_at >= :start_date AND created_at 参数[:start_date], :end_date => 参数[:end_date]})
或
Client.where("created_at IN (?)",
(params[:start_date].to_date)..(params[:end_date].to_date))
如果您的 start_date 是日期字段,那么我要查询从“2010-09-08”开始的所有 TimeSlot。
TimeSlot.where("start_date >= ? AND start_date <= ?", "2010-09-08", "2010-09-08")
如果你的 start_date 是一个日期时间字段。
TimeSlot.where("start_date >= ? AND start_date <= ?", "2010-09-08", "2010-09-09")
因为日期时间从 00:00:00 开始