Question:
Good afternoon.
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, the 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 as [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's wrong?
Answer:
Helped in class CompaniesController
authorize_resource
replaced with load_and_authorize_resource