Reputation: 1608
I'm trying to write a validation for User
that ensures that company.users.where(admin: true).size >= 1
that way if there is only one admin in the company, she can't revoke her admin access and the company is stuck without any admin.
I'm thinking I need to write a validation that checks if the user is changing the admin
to false and if the size of user admins is equal to 1 than give an error message.
This is what I have so far, but I'm not sure how to trigger this with the right type of validation.
def company_have_one_admin_present
errors.add(:admin, 'must have one admin') if 1 == company.users.where(admin: true).size
end
Upvotes: 2
Views: 195
Reputation: 2647
Try adding this to your model, I haven't tested it but I think you can do something like this:
validate :company_have_one_admin_present, on: :update
def company_have_one_admin_present
admins = company.users.where(admin: true)
if !admin? && admins.size == 1 && admins.find_by(id: id)
errors.add(:admin, "at least one admin required")
end
end
This validation only happens if the user is not a new record on: :update
, and that he is currently set to not be an admin !admin?
, but in the database he is actually set as an admin (and the only one for the company) admins.size == 1 && admins.find_by(id: id)
Upvotes: 0
Reputation: 3700
I suggest this solution
class User
validate :company_have_one_admin_present
def company_have_one_admin_present
if persisted? &&
(company.users.where(admin: true).count == 1) &&
(admin_changed? && admin == false)
errors.add(:admin, 'must have at least one admin')
end
end
end
Explanation :
company.users.where(admin: true).count == 1
because count will not
initialize all the users, saving time and memory.admin_changed? && admin == false
means that if you are changing your admin to false, your admin was set to true and therefore you were the only admin ! So whoops no you can't change your admin status !Upvotes: 1