How can I prevent deletion of a "default" entity?

59 views Asked by At

I'm currently building a prototype app, using the latest beta version of Rails 4.2.

For several parts of the system, I need to allow the user to select a "default" item in a list.

So far, I've implemented this as a "default" field on the models, and a uniqueness validation to ensure that there's only one "default" allowed.

One of my business rules is to prevent the deletion of a "default" entity.

I could use a before_destroy callback to do this - and that works fine - but I'm also using the paranoia gem from https://github.com/radar/paranoia to give me soft-delete capabilities. This overrides the destruction of models with an update call (setting a "deleted_at" field instead). Using a before_update call isn't giving me the expected result, as the deleted_at field isn't being set early enough.

If the paranoia gem is going to cause me problems, I'm happy to remove that requirement altogether. Soft deletion is a nice to have, rather than an essential feature at this stage.

Does anyone have any suggestions on how I can implement this logic, and just as importantly test that it works as expected?

1

There are 1 answers

1
user229044 On

You could implement this as a very simple validation that prevents the setting of your deleted_at if the model's default field is set.