紳士なブログ

紳士すぎてすみません

timestampsの自動更新をやめてみる

Railsでのtimestampsの自動更新の正確な挙動を知りたくなったので確認してみた。


activerecord-2.3.12/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
        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)
        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
  end
end


created_atとupdated_atだけかと思ってたらcreated_onとupdated_onも対応してるみたい。地味に。


ActiveRecord::Base.record_timestampsのtrue/falseで自動更新を管理している。例えば、


class Hoge < ActiveRecord::Base
end

Hoge.record_timestamps = false
Hoge.new.save
Hoge.record_timestamps = true


なんてすると、timestampsの自動更新なしにsaveすることができる。


あと余談ですが、create_with_timestamps, update_with_timestampsメソッドを定義してalias_method_chainを使ってるみたい。