views:

33

answers:

2

Hi All, 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 get fail because of any reason (for ex:- Database memmory is full). what will happen in that case? if that creates problem what is better way to avoid it? what update_attribute return if it get failed?

A: 

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
@AboutRuby:- i know what `update_attributes` does i would like to know about `update_attribute`?
Salil
They both do the same thing. Both update_attributes and update_attribute use the attr= assignments and then call save.
AboutRuby
@AboutRuby:- 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
+1  A: 

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
Salil
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