Prevent destruction of objects with associations using CanCan
Sometimes you want to prevent the destruction of objects with associations for certain user roles and this is easy to do if you are using CanCan.
Let us assume that we have two user roles, regular users and administrators. Regular users cannot delete objects with associations but administrators can.
Our ability class will look similar to this:
With the above, you can check if a user can destroy an object by doing the following in a view template:
And last, make sure that you have authorize_resource/load_and_authorize_resource in your controllers (or manually call authorize!(:destroy, @some_obj) before calling destroy on the object.