Active Record 時間戳記
如果資料表有欄位名稱為 created_at/created_on
或 updated_at/updated_on
,Active Record 會自動將建立和更新作業加上時間戳記。
透過設定可以停用時間戳記
config.active_record.record_timestamps = false
預設時間戳記為 UTC,透過設定可以使用當地時區
config.active_record.default_timezone = :local
Time
支援時區的屬性
Active Record 使所有 datetime
和 time
欄位支援時區。預設這些值會儲存在資料庫中,並在從資料庫中提取時轉換回目前的 Time.zone
。
這個功能可以透過設定完全停用
config.active_record.time_zone_aware_attributes = false
同時也可以只設定 datetime
欄位支援時區 (同時 time
值不支援),透過設定下列內容
ActiveRecord::Base.time_zone_aware_types = [:datetime]
也可以新增特定資料庫支援時區的類型。例如 PostgreSQL
ActiveRecord::Base.time_zone_aware_types += [:tsrange, :tstzrange]
最後,能夠針對時區轉換不套用的特定模型屬性,例如透過設定下列內容
class Topic < ActiveRecord::Base
self.skip_time_zone_conversion_for_attributes = [:written_on]
end