obj.update_attribute(:only_one_field, 'Some Value')
obj.update_attributes(field1: 'value', field2: 'value2', field3: 'value3')
Both of these will update an object without having to explicitly tell ActiveRecord to update.
Rails API says:
update_attribute
Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.
update_attributes
Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.
So if I don't want to have the object validated I should use #update_attribute
. What if I have this update on a #before_save
, will it stackoverflow?
My question is does #update_attribute
also bypass the before save or just the validation.
Also, what is the correct syntax to pass a hash to #update_attributes
... check out my example at the top.
update_attribute
statement inside abefore_save
callback? I can't think of a good reason for this. – Daniel Pietzschbefore_save
callback). F.e. instead ofupdate_attribute(:discount, 0.1) if amount > 100
you could dodiscount = 0.1 if amount > 100
.update_attribute
callssave
on the object, which is unnecessary in this case, since the statement is inside abefore_save
callback and will get saved anyway. I hope that makes sense. – Daniel Pietzsch