简体   繁体   English

Rails AR查询中的时间比较问题

[英]Problem with Time Comparison in Rails AR Query

I'm running Rails 3.0.4 with a PostgreSQL Database and i created a DateTime field called ordered_at . 我正在使用PostgreSQL数据库运行Rails 3.0.4,并创建了一个名为ordered_at的DateTime字段。

I set it by creation with Time.now and i want to query the ordered_at field with something like where("ordered_at > ?", params[:later_than] , but if I put later than with something like 1.minute.from_now, I'm getting results where no results should be. 我通过创建Time.now来设置它,我想查询ordered_at字段的内容类似where("ordered_at > ?", params[:later_than] ,但是如果我放的时间晚于1.minute.from_now,我得到没有结果的结果。

In Detail: ordered_at is 2011-03-08 11:11:49 and params[:later_than] is 2011-03-08 11:09:58 UTC . 详情: ordered_at2011-03-08 11:11:49params[:later_than]2011-03-08 11:09:58 UTC

I think that is because of the time zone in the Time object, which doesn't exists in the database (The ordered_At field is a timestamp without time zone Datatype). 我认为这是因为Time对象中的时区在数据库中不存在(ordered_At字段是timestamp without time zone数据类型的timestamp without time zone )。

Does anyone had the same problem and can help me? 有没有人有同样的问题,可以帮助我?

Fixed it. 修复。 The root of evil was in my fixtures. 邪恶的根源在我的固定装置中。

You have to set times in your fixtures like that: 你必须在你的灯具中设置这样的时间:

  ordered_at: <%= (30.minutes.ago).iso8601 %>

otherwise you will get the timezone of the database/server 否则你将获得数据库/服务器的时区

The thing you have to remember is Rails store the time in your database in UTC. 您必须记住的事情是Rails以UTC格式存储数据库中的时间。 Rails convert the time into UTC and sets it as the standard to look at in the database. Rails将时间转换为UTC并将其设置为数据库中要查看的标准。 So if you have params[:later_than] as 2011-03-08 11:11:49 UTC or any time for that matter with any time zone, Rails will convert it into UTC time zone before inserting into the SQL query. 因此,如果您将params[:later_than]作为2011-03-08 11:11:49 UTC或任何时区的任何时间区域,Rails会在插入SQL查询之前将其转换为UTC时区。 If you are saving Time.now into the database, Time.now will be the server time or local machine time with the time zone in which the machine is set. 如果要将Time.now保存到数据库中, Time.now将是服务器时间或本地计算机时间以及设置计算机的时区。 Before saving to database, Rails will convert it to UTC and save it. 在保存到数据库之前,Rails会将其转换为UTC并保存。 So, at database level everything will be converted to UTC and then will be compared so avoiding confusion. 因此,在数据库级别,所有内容都将转换为UTC,然后进行比较,以避免混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM