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

时间:2015-09-22 13:09:27

标签: ruby-on-rails ruby-on-rails-4 cancancan

在我的应用程序中,用户可能有很多公司,并且可以在公司中拥有不同的权限以进行粗暴操作,现在我使用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?

1 个答案:

答案 0 :(得分:0)

如果我理解你的话,它会对你有所帮助:

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

并使用它:

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