2

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

用户.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

角色.rb

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

用户角色.rb

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

能力.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?

4

1 回答 1

0

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

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

并使用它:

if can? :manage, @company
  # do something
end
于 2015-09-22T13:22:05.710 回答