Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `update_attribute` return if it fails?

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?

like image 740
Salil Avatar asked Aug 26 '10 10:08

Salil


2 Answers

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.

like image 124
mikej Avatar answered Oct 09 '22 15:10

mikej


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.

like image 35
AboutRuby Avatar answered Oct 09 '22 16:10

AboutRuby