Good day.

class ability

can :manage, Company do |company| user.available_roles.include?(company.role) end 

class User

 belongs_to :company delegate :admin?, :operator?, :agent?, :sales?, :visitor?, :available_roles, :role, to: :company 

class Company

 has_many :users def admin? role == 'admin' end def operator? role == 'operator' end def agent? role == 'agent' end def sales? role == 'sales' end def visitor? role == 'visitor' end def available_roles case role when 'admin' %w[visitor sales agent operator admin] when 'operator' %w[visitor sales agent] else [] end end 

class CompaniesController

  authorize_resource def new @company = Company.new respond_with @company end def create @company = Company.create(company_params) respond_with @company end 

When creating Companies, Admin can define the role of companies %w[visitor sales agent operator admin]

When creating Companies, the Operator can only define the role of companies [visitor sales agent]

Through the console: User.last is a user with operator rights

 » Ability.new(User.last).can? :manage, Company.new(role: :admin, name: 'Company Administrator') User Load (1.5ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1 Company Load (0.8ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1 [["id", 4]] # false » Ability.new(User.last).can? :manage, Company.new(role: :agent, name: 'Company Agent') User Load (1.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1 Company Load (0.5ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1 [["id", 4]] # true 

But through the web interface, the operator can create a company with the role of admin and operator ,

Please tell me what is wrong?

    2 answers 2

    Helped in class CompaniesController

    authorize_resource replaced by load_and_authorize_resource

      user.rb

       attr_accessor :current_user 

      And in UsersController you need to add current_user to the parameters:

       User.new user_params.merge(current_user: current_user) ... User.update user_params.merge(current_user: current_user) 

      But this is not the best solution, it is better to give the right to create in the controller or service.

      • Changed the question. - Mikhail Lutsko