What does `update_attribute` return if it fails?
Asked Answered
K

2

6

I have following piece of code

@user = User.find(params[:id])
if (@user.activation_status == "active") 
  #some code here 
  @user.update_attribute('activation_status' ,'inactive')  # Line 44
  #send mail to user that his account is Acivated
else

end

Is there any chance that Line 44 could fail? Because database memory is full or network failure. What will happen in that case? If that creates a problem, what is a better way to avoid it? What does update_attribute return if it failed?

Kajdan answered 26/8, 2010 at 10:30 Comment(0)
R
6

Here is the source for update_attribute:

def update_attribute(name, value)
  send(name.to_s + '=', value)
  save(false)
end

You can see that it updates the requested attribute and then calls save with perform_validations set to false. Therefore update_attribute would return false if any of the save callbacks (e.g. before_save) prevented the record from being saved by returning false.

If there was a lower level error such as out of memory at the database then I expect the database driver to raise this as an exception which would be passed up to your code.

Rodenticide answered 26/8, 2010 at 11:25 Comment(2)
what update_attribute will return i know what update_attributes does? update_attribute && update_attributes are two different methods. I would like to know about update_attributeKajdan
This answer is referring to update_attribute, I had made a typing mistake in the original version of the answer. update_attribute returns the value returned by save, as described in the answer.Rodenticide
H
1

If update_attributes fails, it will return false. if you ignore the return value, you'll have no idea it happened either. You can use update_attributes!, which in turn calls save!, which in turn raises an exception if something goes wrong. While this is something you can't miss (unless you write catch-all rescue statements), if you don't catch it, it will fall through to Rails, and it will abort the request.

It's usually a good idea to check the return value.

Here answered 26/8, 2010 at 11:9 Comment(3)
- i know what update_attributes does i would like to know about update_attribute?Kajdan
They both do the same thing. Both update_attributes and update_attribute use the attr= assignments and then call save.Here
- You are wrong they don't do same thing update_attributes check validation before saving data and return false is object is invalid and true if it saved whereas update_attribute save data w/o checking validations.Kajdan

© 2022 - 2024 — McMap. All rights reserved.