Search code examples
htmlruby-on-railsrubydevise

Only one principal(user) can be created by role attribute which is enum + rails


i am new to rails and creating a school app where i have given an attribute role to user which is deciding the role of user and i want to create only one user can be principal(role), how do i achieve that there can not be create more than one principal user in app, i am using devise for authentication...

i tried this => validates :role, :uniqueness => { :role => "principal" }

but it is restricting me from creating any kind of user , in my user enum i have given 4 roles [admin,principal,teacher,student]

any help or advice will be appreciated.... thanks in advance


Solution

  • I would use a custom validation like this:

    validate :one_principal_exists
    
    private
    
    def one_principal_exists
      return unless principal?
      return unless User.where.not(id: id).exists?(role: 'principal')
    
      error.add(:role, 'already exists')
    end
    

    The idea is to check first if the current user is a principal, if not skip the validation. And then check if there is already another user (who has a different id than the current user) in the database who has the principal role. If such a user exists, then add a validation error to the role attribute.

    Please note that you might need to add more conditions to the database query when you, for example, want to support multiple schools and each school has a different principal.