0

I need to override the rails update_all method so that it will update updated_at field for specific models.

I have added following module in app/config/intializer/xyzfile.rb :

module ActiveRecord
  class Relation
    def update_all_with_updated_at(updates)
      case updates
        when Hash
          updates.reverse_merge!(updated_at: Time.now)
        when String
          updates += ", updated_at = '#{Time.now.to_s(:db)}'"
        when Array
          updates[0] += ', updated_at = ?'
          updates << Time.now
      end
      update_all_without_updated_at(updates)
    end
    alias_method_chain :update_all, :updated_at
  end
end

I want to use this for specific models, How can I do this?

  • Adding updated_at in each update_all is one of the solutions but I am looking for a solution with which I can override update_all method.
Prajakta
  • 101
  • 1
  • 4
  • Why not just call the `update_all` method with `updated_at: Time.zone.now` (or add it to an existing hash)? – Jiří Pospíšil Jan 12 '15 at 09:54
  • @JiříPospíšil This is one of the solution. But with this, I will need to add updated_at in each update_all statement for all required models. So I am looking for a solution with which I can override update_all method. – Prajakta Jan 12 '15 at 09:59

1 Answers1

-1

Put the following code in a file /config/initializers/update_all_with_touch.rb Place this block of code in

app/config/intializer/update_all_decorate.rb

class ActiveRecord::Relation

  def update_all_decorate(updates, conditions = nil, options = {})

    current_time = Time.now

    # Inject the 'updated_at' column into the updates
    case updates
      when Hash;   updates.merge!(updated_at: current_time)
      when String; updates += ", updated_at = '#{current_time.to_s(:db)}'"
      when Array;  updates[0] += ', updated_at = ?'; updates << current_time
    end

  end
  alias_method_chain :update_all, :touch
end

alias_method_chain block is responsible for overriding the default behavior of update_all method.

Ajay
  • 4,199
  • 4
  • 27
  • 47
  • I have added code similar to this, but I want to override behavior of update_all for specific models and not for all. – Prajakta Jan 12 '15 at 09:50