created_at是怎么计算出来的?

How is created_at calculated?

当我创建一个新的 ActiveRecord 实例时,created_at 时间戳被保存到数据库中。

下面是来自 ActiveRecord 的 _create_record 方法的实现:

def _create_record
  if record_timestamps
    current_time = current_time_from_proper_timezone

    all_timestamp_attributes_in_model.each do |column|
      if !attribute_present?(column)
        _write_attribute(column, current_time)
      end
    end
  end

  super
end

下面是 current_time_from_proper_timezone 方法的实现:

def current_time_from_proper_timezone
      default_timezone == :utc ? Time.now.utc : Time.now
end
  • 时间戳默认为 UTC(使用 Time.now.utc 计算),但是可以在您的配置中更改 config.active_record.default_timezone = :local(在这种情况下,它将使用 Time.now)

  • 时间以你的服务器为准

  • 默认为 UTC,但您可以通过设置 config.active_record.default_timezone = :local

  • 更改它

如果您想查看代码,这里是 link:https://github.com/rails/rails/blob/master/activerecord/lib/active_record/timestamp.rb