0
votes

I have two entities. User and Role. I am using Devise and CanCan. They are in a many to many relationship.

User has a lot of roles. One of the roles is "Administrator". I verify if my user is an administrator using:

if (user.role? :administrator) .... #this is already implemented and working

I have to validate that never exists more than 2 administrator in the same department on the system. For that purpose I created a custom validate method:

class User < ActiveRecord::Base
    validate :maximum_numbers_of_admins if self.role? :administrator
    belongs_to :department

    def maximum_numbers_of_admins
        #Some code here
    end

In that method I should count the number of Users that have role administrator (without counting myself). I don't know how to set the :conditions of my find method to get this number.

This is the specification of the Role class:

# == Schema Information
#
# Table name: roles
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime
#

There is a many to many relationship between users and Roles. (Table roles_users) Any help with that?

Thanks

1
con you post the Role fields please? - tommasop
yeah I guessed it was name. My answer should do the trick. - tommasop
I commented your answer below. - Tony
Hi Tony from Role table definition you can't have a many to many relation with User model you lack the user_id field - tommasop

1 Answers

2
votes

It could be something along this lines:

def maximum_numbers_of_admins
    if Role.find(:conditions => ['name = ?', 'Administrator']).users.count < 2
      return true
    else
      return false
    end
end