Reputation: 953
Hi I am using cancan gem for the first time. I have included this in my gem file
gem 'cancancan', '~> 1.10'
then done bundle install and run command rails g cancan:ability through which my ability.rb is generated in which I have given this code
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
and in my application_Controller given this
rescue_from CanCan::AccessDenied do |exception|
flash[:error] = "Access denied."
redirect_to root_url
end
Now I have sign in with employee[:role]= 'HR' and when I am going to create departments then it gives me error
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'
Please guide me how to solve this. Thanks in advance.
Upvotes: 1
Views: 109
Reputation: 1465
You have to override the current_ability method in application_controller.rb
def current_ability
@current_ability ||= Ability.new(your_current_logged_in_employer_object)
end
Upvotes: 1