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?
相关问题
- Question marks after images and js/css files in ra
- Using :remote => true with hover event
- Disable Browser onUnload on certain links?
- Eager-loading association count with Arel (Rails 3
- How to specify memcache server to Rack::Session::M
相关文章
- Ruby using wrong version of openssl
- Right way to deploy Rails + Puma + Postgres app to
- AWS S3 in rails - how to set the s3_signature_vers
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- How to add a JSON column in MySQL with Rails 5 Mig
- How to create a CFuncType in Python
- “No explicit conversion of Symbol into String” for
Use ActiveRecord context validation in Rails 5.
just a note:
For rails 3
You can wrap the destroy action in an "if" statement in the controller:
Where valid_destroy? is a method on your model class that returns true if the conditions for destroying a record are met.
Having a method like this will also let you prevent the display of the delete option to the user - which will improve the user experience as the user won't be able to perform an illegal operation.
You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.
For example:
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.
myBooking.destroy
will now return false, andmyBooking.errors
will be populated on return.The ActiveRecord associations has_many and has_one allows for a dependent option that will make sure related table rows are deleted on delete, but this is usually to keep your database clean rather than preventing it from being invalid.
I ended up using code from here to create a can_destroy override on activerecord: https://gist.github.com/andhapp/1761098
This has the added benefit of making it trivial to hide/show a delete button on the ui