Tom Lehman Tom Lehman - 4 months ago 14
Ruby Question

Manually set updated_at in Rails

I'm migrating my old blog posts into my new Rails blog, and I want their

updated_at
attribute to match the corresponding value on my old blog (not the date they were migrated into my new Rails blog).

How can I do this? When I set
updated_at
manually it gets overridden by the
before_save
callback.

Answer

If it's a one time thing you can turn record_timestamps on or off.

ActiveRecord::Base.record_timestamps = false

#set timestamps manually

ActiveRecord::Base.record_timestamps = true

When I ran into this issue with my app, I searched around for a bit and this seemed like it made the most sense to me. It's an initializer that I can call where I need to:

module ActiveRecord  
  class Base  

    def update_record_without_timestamping  
      class << self  
        def record_timestamps; false; end  
      end  

      save!  

      class << self  
        def record_timestamps; super ; end  
      end  
    end  

  end  
end