update_attributes_if_changed

September 28th, 2006

Update_attributes is not very smart; it will update a record whether or not the hash you pass it contains any changed values. If you aren’t careful, you could end up with a ton of database writes for no reason. Try my update_attributes_if_changed method instead:

module ActiveRecord
  class Base
    
    def update_attributes_if_changed(hash)
      update_attributes(hash) if needs_update?(hash)
    end
    
    def needs_update?(hash)
      hash.stringify_keys!
      !attributes.dup.delete_if{|k,v| !hash.key?(k) || hash[k] == v}.empty?
    end

    def(hash)
      attributes.merge(hash.stringify_keys)
    end

  end
end

I’ve thrown in a method called write_attributes too. It works just like update_attributes, but it doesn’t automatically save the record.