D
D
dexdev2017-03-26 17:34:57
Ruby on Rails
dexdev, 2017-03-26 17:34:57

How to properly determine the role using the cancancan gem?

Good afternoon!
Prompt as correctly to define the rights of the user.
I am writing an application for document management between companies, a user can have many companies, a company can have many users, the user has the rights to administer the organization, send documents, create documents. I did everything as follows from the gems I chose Devise, Cancancan, rolify

Class User < ActiveRecord::Base
  rolify strict: true
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :companies, through: :users_companies
  has_many :users_companies
  has_and_belongs_to_many :roles, :join_table => :users_roles
end

class Role < ActiveRecord::Base
  resourcify
  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true

  scopify
end

class Company < ActiveRecord::Base
  resourcify
  devise :database_authenticatable, :registerable
  has_many :users_companies
  has_many :users, through: :users_companies
end

with the addition of rights to the user, it seems everything is clear to add rights User.add_role (: admin, current_company), adds a role indicating which company this role belongs to, but with ability I don’t know how to determine whether the user belongs to a company
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # in case of guest
  if user.has_role? :super_admin
    can :manage, :all
  else
    can :read, :all
  end
  if user.has_role? :admin
    can :manage, Company # не знаю как тут проверять есть ли у пользователя роль в этой компании и какая логика у проверки? что он делает и каким образом не понятно
  end
  end
end

Tell me what to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2017-03-26
@Dem1

can :update, Company do |company|
  user.has_role?(:admin, company)
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question