migrate時にtimestampsカラムを追加しておけば(scaffoldでは自動で設定される)
登録・更新時にcteated_at, updated_atなどに自動で設定される。
このカラム名を変更したいと思いソースを見てみた。
ソース
#gems/activerecord-2.3.11/lib/active_record/timestamp.rb
module ActiveRecord module Timestamp def self.included(base) #:nodoc: base.alias_method_chain :create, :timestamps base.alias_method_chain :update, :timestamps base.class_inheritable_accessor :record_timestamps, :instance_writer => false base.record_timestamps = true end private def create_with_timestamps #:nodoc: if record_timestamps current_time = current_time_from_proper_timezone write_attribute('created_at', current_time) if respond_to?(:created_at) && created_at.nil? write_attribute('created_on', current_time) if respond_to?(:created_on) && created_on.nil? write_attribute('updated_at', current_time) if respond_to?(:updated_at) && updated_at.nil? write_attribute('updated_on', current_time) if respond_to?(:updated_on) && updated_on.nil? end create_without_timestamps end def update_with_timestamps(*args) #:nodoc: if record_timestamps && (!partial_updates? || changed?) current_time = current_time_from_proper_timezone write_attribute('updated_at', current_time) if respond_to?(:updated_at) write_attribute('updated_on', current_time) if respond_to?(:updated_on) end update_without_timestamps(*args) end
alias_method_chainでcreate/updateを変更しています。
なるほど
ではコレをoverrideすればいいのかと
config/environment.rbに記載してみるもNG。
なぜかoverrideされない。
ActiveRecord::Baseでincludeしてるから?
ここよく分かんない。
じゃ
ActiveRecord::Baseに対してoverrideしてみた。
カラム名はそれぞれ、add_date, upd_dateに変更。
module ActiveRecord class Base private def create_with_my_timestamps if record_timestamps current_time = current_time_from_proper_timezone write_attribute('add_date', current_time) if respond_to?(:add_date) && add_date.nil? write_attribute('upd_date', current_time) if respond_to?(:upd_date) && upd_date.nil? end create_without_my_timestamps end alias_method_chain :create, :my_timestamps def update_with_my_timestamps(*args) if record_timestamps && (!partial_updates? || changed?) current_time = current_time_from_proper_timezone write_attribute('upd_date', current_time) if respond_to?(:upd_date) end update_without_my_timestamps(*args) end alias_method_chain :update, :my_timestamps end end
とりあえず
できたけど、、、。
ActiveRecord::Timestamp を修正する方が健全な気がするんだけど
どうやってやるんだろう。