Rails has many built in validation methods to ensure that an
ActiveRecord instance cannot be created or updated under certain
situations (typically caused by invalid data). However, I can find no
methods to govern whether an ActiveRecord instance can be destroyed.
Essentially, I wish an error to be raised when a user tries to delete an
ActiveRecord without first adhering to a certain set of conditions. I
currently achieve this via before_destroy method, where I set a custom
error for the ActiveRecord in question. I then persist the ActiveRecord
across the session, so that I can redirect from ‘delete’ to ‘list’ as
usual without losing the error in the process. To display the error, I
use an overridden error_messages_for, so that the header will say “from
being deleted” instead of “from being saved”.
This all seems a remarkably round about way of doing things for what
must be a not uncommon problem. Is there a more “Rails-like” way of
doing this? Has anyone else come across the problem where an error
message should be raised if the user attempts to delete something
important without doing X, Y and Z first?
Thanks in advance,
- James Reeves