Best way to update attributes on AR objects without saving?

Wes Gamble wrote:

All,

In some cases, one may not want to save attributes retrieved from a form to the database right away. Would the best way to bulk update your AR object from the params hash be to do:

@ar_obj.attributes.merge!(params[:appropriate_key])

@ar_obj.attributes = params[:appropriate_key]

is all you need. The only attributes set are those named by keys in the params hash.

Wes Gamble wrote:

Mark Reginald James wrote:

@ar_obj.attributes = params[:appropriate_key]

is all you need. The only attributes set are those named by keys in the params hash.

Shouldn't you merge the keys, given the possibility that your object may have an unsaved attribute set already (that you want to keep) that is not represented in your params hash. Using = will blow away those attributes, but merge! will preserve them.

No, the attributes= method does not assign a new attribute hash. It just assigns new values to the attributes (and attr_accessors) keyed in the RHS hash.

Actually it doesn't blow them away. That's something that I forget every single time I use it.

Also, because merge! is a method on Hash, using that will bypass things like attr_protected, which you don't want.

Pat