I've got Rails 7 app with AdminUser
model. There can be multiple Admins in which anyone can remove any administrator. How do I set the validation so that it blocks the possibility of deleting AdminUser
if this one is the last one in the db?
In a nutshell I want to have always one undelitable AdminUser.
CodePudding user response:
First of all, I would add an AdminUser#destroyable?
to allow checking in the frontend if a destroy is possible and if a link should be rendered in the view.
# in app/models/admin_user.rb
def destroyable?
AdminUser.count > 1
end
This can be used in the view like this:
<%= link_to(admin_user_path ...) if admin_user.destroyable? %>
Then you can raise an exception when someone tries to destroy the last admin user.
# in app/models/admin_user.rb
before_destoy :do_not_destroy_last_admin
private
def do_not_destroy_last_admin
raise(
ActiveRecord::RecordNotDestroyed, "Last admin cannot be deleted"
) unless destroyable?
end
CodePudding user response:
Use a callback like before_destroy
.
class AdminUser < ApplicationRecord
before_destroy :check_last
...
private
def check_last
return unless AdminUser.size < 2
raise ActiveRecord::RecordNotDestroyed, 'Can\'t delete last Admin'
end
end