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?

Lex
  • 4,749
  • 3
  • 45
  • 66
Salil
  • 46,566
  • 21
  • 122
  • 156

2 Answers2

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.

mikej
  • 65,295
  • 17
  • 152
  • 131
  • 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_attribute` – Salil Aug 26 '10 at 11:31
  • 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. – mikej Aug 26 '10 at 11:43
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.

AboutRuby
  • 7,936
  • 2
  • 27
  • 20
  • - i know what `update_attributes` does i would like to know about `update_attribute`? – Salil Aug 26 '10 at 11:14
  • They both do the same thing. Both update_attributes and update_attribute use the attr= assignments and then call save. – AboutRuby Aug 26 '10 at 11:27
  • 1
    - 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. – Salil Aug 26 '10 at 11:34