Check if ActiveRecord object is destroyed using the .destroy() return value

highBandWidth picture highBandWidth · Sep 28, 2012 · Viewed 7.9k times · Source

I am maintaining someone's code base and they have something like this:

if @widget_part.destroy
  flash[:message] = "Error deleting widget part"
else
  flash[:message] = "Widget part destroyed successfully"
end

What does destroy return? Is it ok to test like this? The reason I'm asking is that I tried to use

flash[:message] = "Error deleting widget part : #{@widget_part.errors.inspect}"

and there are no error messages so I am confused. It gives something like

#<ActiveModel::Errors:0x00000103e118e8 @base=#<WidgetPart widget_id: 7, ..., 
  id: 67>, @messages={}>

Answer

sheerun picture sheerun · Sep 28, 2012

If you're unsure, you can use destroyed? method. Return value of destroy is undocumented, but it returns just freezed destroyed object (you cannot update it). It doesn't return status of destroy action.

Although generally destroying object should always succeed, you can listen for ActiveRecordError. For example Optimistic Locking can raise ActiveRecord::StaleObjectError on record destroy.