1

I have a Tweet model. I want to update the model attributes but without updating the timestamp.

I've already read/tried some links and didn't work for me:

I tried to override ActiveRecord::Base as mentioned in the second link, by creating a new file active_record_base_patches.rb inside lib directory. But, the engine said that the method was not found in Tweet model.

So, I tried to move the update_record_without_timestamping to Tweet model. The method is found now but the timestamp is updated.

Is there any simple method to disable timestamp in Rails for a while? Laravel 4 has something like this: https://stackoverflow.com/a/18906324/3427434.

PS: I use Ruby on Rails 4.2.3 on Ruby 2.2.0.

Community
  • 1
  • 1
Edward Samuel
  • 3,846
  • 1
  • 22
  • 39

1 Answers1

2

You could create concern in model/concern, named it with model_timestamp.rb

require 'active_support/concern'

module ModelTimestamp
  extend ActiveSupport::Concern

  module ClassMethods
    def without_timestamps
      old = ActiveRecord::Base.record_timestamps
      ActiveRecord::Base.record_timestamps = false
      begin 
        yield 
      ensure
        ActiveRecord::Base.record_timestamps = old
      end
    end
  end
end

Then in your model Tweet add include ModelTimestamp

class Tweet < ActiveRecord::Base
  include ModelTimestamp

  ...
end

Then where you want to update your attributes without timestamps to change use

tweet = Tweet.last
Tweet.without_timestamps do
  tweet.update(attributes)
end
Edward Samuel
  • 3,846
  • 1
  • 22
  • 39
Nermin
  • 6,118
  • 13
  • 23
  • I tried your solution, it didn't work. I noticed a trigger: `on update CURRENT_TIMESTAMP` in a column. After I removed the trigger, I tried your solution once more, and it is working now. – Edward Samuel Jul 14 '15 at 12:08