您好我第一次使用康康宝石。我把它包含在我的宝石文件中
gem 'cancancan', '~> 1.10'
然后完成了bundle install并运行命令 rails g cancan:ability ,通过它我生成了我的能力.rb,我已经给出了这段代码
class Ability
include CanCan::Ability
def initialize(employee)
employee ||= Employee.new
if employee[:role]== 'HR'
can :manage, :all
else
can :read, :all
end
end
end
并在我的application_Controller中给出了这个
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = "Access denied."
redirect_to root_url
end
现在我已登录员工[:role] ='HR',当我要创建部门时,它会给我错误
NameError (undefined local variable or method `current_user' for #<DepartmentsController:0xb48a0c0>):
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_additions.rb:357:in `current_ability'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:215:in `current_ability'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:98:in `initial_attributes'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:91:in `assign_attributes'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:86:in `build_resource'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:66:in `load_resource_instance'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:32:in `load_resource'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:25:in `load_and_authorize_resource'
vendor/ruby/2.1.0/gems/cancancan-1.10.1/lib/cancan/controller_resource.rb:10:in `block in add_before_filter'
请指导我如何解决这个问题。提前谢谢。
答案 0 :(得分:1)
您必须覆盖application_controller.rb
中的current_ability方法def current_ability
@current_ability ||= Ability.new(your_current_logged_in_employer_object)
end