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={}>
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With