TrevDroid
TrevDroid

Reputation: 85

Ruby on Rails rolify creates new roles instead of reusing current roles

I'm using rolify cancan and devise gem with ROR. I'm currently trying to add 3 types of roles admin, employer and employee. When I execute the following commands:

user = User.find(1)
user.add_role("employee")

The role gets created and added however if I repeat the steps with a new user it creates a the second user with a new role. Should it not use the same role?

enter image description here

Here is the code: User.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  rolify
  
  extend Devise::Models
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :fullname, presence: true

  has_many :posts
  has_many :applications
  has_many :users, through: :applications
  has_one_attached :image

  has_many :employee_reviews, class_name: "EmployeeReview", foreign_key: "employee_id"
  has_many :employer_reviews, class_name: "EmployerReview", foreign_key: "employer_id"

  def employer?
      has_role?(:employer)
  end

  def employee?
    has_role?(:employee)
  end 

end

Role.rb

class Role < ApplicationRecord
  has_and_belongs_to_many :users, :join_table => :users_roles
  
  belongs_to :resource,
             :polymorphic => true,
             :optional => true
  

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end

Upvotes: 0

Views: 222

Answers (1)

TrevDroid
TrevDroid

Reputation: 85

To set the role as employee and not recreate use the followig steps

user = User.find(1) user.add_role(:employee)

Upvotes: 0

Related Questions