I did not know about write_attribute until today...
it seems like update_attribute, although not calling validation is still calling the :before_save callbacks, whereas write_attribute doesn't.
Is that the difference between these two methods?
All of these will update an object in a database without having to explicitly tell AR to update. update_attribute can update only one column. Use update_attribute to skip validations. update_attribute uses save(false) while update_attributes uses save (which means save(true)).
This method used to be called update_attributes in Rails 3. It changes the attributes of the model, checks the validations, and updates the record in the database if it validates. Note that just like update_attribute this method also saves other changed attributes to the database.
Use update_attribute to change an attribute and persist it without running validations. Use update to change an attribute, check the validations and persist the change if validations pass. You can find an object and update it with a one command using update as class method.
update_attribute
actually makes a physical call to the DB. You get a full execution of an UPDATE
statement. It's like update_attributes
but just for a single column.
While write_attribute
writes the attribute for assignment to the model for AR based columns. If you were to overwrite a DB based attribute.
def first_name=(val)
write_attribute :first_name, val
end
# some_model.first_name => 'whatever val is'
def first_name=(val)
@first_name = val
end
# some_model.first_name => nil
I have not looked into write_attribute
extensively, but I gather Activerecord based models handle assignments to db based columns slightly differently than your run of the mill accessor.
write_attribute
is used when you want to overwrite the default accessors for a method. It is essentially syntactic sugar for self[:attribute]=(value)
.
Have a look at the ActiveRecord::Base documentationunder the heading "Overwriting default accessors".
If you tried to rewrite the example in the documentation using update_attribute
, I'd imagine it would end up in a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With