Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3: difference between write_attribute and update_attribute

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?

like image 824
standup75 Avatar asked May 27 '11 22:05

standup75


People also ask

What is difference between update Update_attributes?

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)).

What does Update_attributes do?

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.

How do you update attributes in Ruby on Rails?

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.


2 Answers

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.

like image 131
nowk Avatar answered Oct 21 '22 18:10

nowk


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.

like image 29
Douglas F Shearer Avatar answered Oct 21 '22 17:10

Douglas F Shearer