是的,您可以直接将created_at ActiveRecord 日期/时间字段的值与常规DateTime 对象(就像您可以通过解析字符串获得的对象一样)进行比较。
在一个项目中,我有一个 Value 对象,它有一个 created_at 日期时间对象:
imac:trunk luca$ script/console
Loading development environment (Rails 2.3.2)
>> Value.first.created_at
=> Fri, 12 Jun 2009 08:00:45 CEST 02:00
>> Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> Wed Jun 03 22:57:45 0200 2009
>> Value.first.created_at > Time.parse("2009-06-03 16:57:45.608000 -04:00")
=> true
created_at 字段定义为:
create_table "values", :force => true do |t|
[...]
t.datetime "created_at"
end
注意如果您的字段是日期而不是日期时间,则需要将其转换为时间:
Post.first.created_at.to_time > Time.parse("2009-06-03 16:57:45.608000 -04:00")
或解析日期:
Post.first.created_at > Date.parse("2009-06-03 16:57:45.608000 -04:00")
否则你会得到:
ArgumentError: comparison of Date with Time failed