如果用户有多个公司,如何向用户添加角色



在我的应用程序中,用户可能有许多公司,并且可以在公司中对crud操作有不同的权限,现在我使用cancancan gem和授权如下:

User.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :companies, through: :users_companies
  has_many :users_companies
  has_many :users_roles, dependent: :destroy
  has_many :roles, through: :users_roles
  validates :first_name, :last_name, presence: true
  def has_role?(role_sym)
    roles.any? { |r| r.name.underscore.to_sym == role_sym }
  end
end

Role.rb

class Role < ActiveRecord::Base
  has_many :users_roles
  has_many :users, through: :users_roles
end

UsersRole.rb

class UsersRole < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
  #belongs_to :company
end

Ability.rb

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new # in case of guest
  if user.has_role? :admin
    can :manage, :all
  else
    can :read, :all
  end
  if user.has_role? :moderator
    can :manage, Company
  else
    can :read, :all
  end
    end
end

现在当用户选择另一个公司用户可以管理公司模型,但没有在另一个公司的权限,如何检测公司id的用户?

如果我理解你的正确,它会帮助你:

can :manage, Company { |company| user.company_id == company.id }

并使用它:

if can? :manage, @company
  # do something
end

最新更新