我手动更改这些列,提取时间值的时区信息。
我在想Rails框架中是否有使用这两列的内部规则。
手动更改它们是否安全?我正在使用此代码:
module ActiveRecord
class Base
before_save :update_autocolumns
def update_autocolumns
if (!self.id) #inserting
if (self.respond_to? :created_at)
self.created_at = Time.now.ttz
end
end
if (self.respond_to? :updated_at)
self.updated_at = Time.now.ttz
end
end
end
end
这个“ttz”方法用于从时间列中提取时区:
def ttz
self.strftime('%a, %d %b %Y %H:%M:%S').to_time
end
答案 0 :(得分:0)
是的,您可以查看Timestamps
module中的代码。你的代码只是多余的。
这些属性将在更新时自动更新。
def timestamp_attributes_for_update
[:updated_at, :updated_on]
end
这些属性将在创建时自动更新。
def timestamp_attributes_for_create
[:created_at, :created_on]
end
这是文档。
# = Active Record Timestamp
#
# Active Record automatically timestamps create and update operations if the
# table has fields named <tt>created_at/created_on</tt> or
# <tt>updated_at/updated_on</tt>.
#
# Timestamping can be turned off by setting:
#
# config.active_record.record_timestamps = false
#
# Timestamps are in UTC by default but you can use the local timezone by setting:
#
# config.active_record.default_timezone = :local
#
# == Time Zone aware attributes
#
# By default, ActiveRecord::Base keeps all the datetime columns time zone aware by executing following code.
#
# config.active_record.time_zone_aware_attributes = true
#
# This feature can easily be turned off by assigning value <tt>false</tt> .
#
# 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