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

I maintain a 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 returns destroy ? Can this be tested? The reason I ask is because I tried to use

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

and no error messages, so I'm confused. It gives something like

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

If you are not sure, can you use the destroyed? method destroyed? . The return value of destroy is undocumented, but it returns only a frozen destroyed object (you cannot update it). It does not return the destroy action status.

Although a normally killing object should always succeed, you can listen to an ActiveRecordError . For example, Optimistic locking can raise ActiveRecord :: StaleObjectError when deleting a record.

+5
source

As mentioned above, destroy does not return a boolean; instead, it returns a frozen object. In addition, it updates the state of the instance object that you call it on. This is how I write the controller:

 @widget_part.destroy if @widget_part.destroyed? flash[:success] = 'The part is destroyed' else flash[:error] = 'Failed to destroy' end 
+3
source

According to the Ruby on Rails API, the destroy method returns the object that you destroyed, but in a frozen state.

When an object is frozen, changes to the object should not be made since it can no longer be saved.

Can you check if an object has been destroyed with object.destroyed? .

+1
source

All Articles