Posted on September 28, 2006 at 10:25 am

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 write_attributes(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.

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>