Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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={}>
like image 583
highBandWidth Avatar asked Sep 28 '12 20:09

highBandWidth


People also ask

How do you destroy a record in rails?

Rails delete operation using destroy methodBy using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

What is the difference between delete and destroy in rails?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

What is an ActiveRecord object?

In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic as part of the object will educate users of that object on how to write to and read from the database.


1 Answers

As some people mentioned above, that destroy does not return a boolean value, instead it returns a frozen object. And additionally it does update the state of the instance object that you call it on. Here 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
like image 120
Trung Lê Avatar answered Sep 26 '22 03:09

Trung Lê