Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 'validate' on destroy in rails

On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?

like image 515
Stephen Cagle Avatar asked Sep 23 '08 19:09

Stephen Cagle


People also ask

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

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.

How do you destroy 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 dependent destroy in rails?

If you set the :dependent option to: :destroy, when the object is destroyed, destroy will be called on its associated objects. :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.


1 Answers

You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.

For example:

class Booking < ActiveRecord::Base   has_many   :booking_payments   ....   def destroy     raise "Cannot delete booking with payments" unless booking_payments.count == 0     # ... ok, go ahead and destroy     super   end end 

Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.

def before_destroy   return true if booking_payments.count == 0   errors.add :base, "Cannot delete booking with payments"   # or errors.add_to_base in Rails 2   false   # Rails 5   throw(:abort) end 

myBooking.destroy will now return false, and myBooking.errors will be populated on return.

like image 161
Airsource Ltd Avatar answered Sep 20 '22 14:09

Airsource Ltd