如何使用rails3将本地时区的日期保存到db?
我有模型用户的Rails3应用程序和字段expires_at创建如下:
t.column :expires_at, :timestamp
在我的数据库(postgresql)中它有类型:
timestamp without timezone
问题是我打电话的时候:
@user.expires_at = Time.now @user.save
它使用UTC时区保存到数据库中(我的当地时间是UTC + 1:00,华沙),但我不希望这样。 我只想把我的本地时区保存到数据库中(2011-03-30 01:29:01.766709,而不是2011-03-29 23:29:01.766709)
我可以使用rails3实现这个目标吗?
为了节省本地时区到数据库的时间,必须在application.rb中设置
config.active_record.default_timezone = :local
如果您只想在某些列上使用本地时间,而不是作为全局设置,那么Rails文档告诉我们:
# If your attributes are time zone aware and you desire to skip time zone conversion to the current Time#zone when reading certain attributes then you can do following: class Topic < ActiveRecord::Base self.skip_time_zone_conversion_for_attributes = [:written_on] end
(这也会在写作时跳过时区转换,而不仅仅是阅读)。 并且您可以为多个属性传递符号数组。
不过,我不确定引入哪种版本的Rails。