I am trying to use cancancan gem in rails. I have a controller named CPController
inside which I have declared load_and_authorize_resource
. Another controller ParticipantsController
inherits from this controller. Inside the ParticipantsController
I want to override this specific functionality such as load_and_authorize_resource class: 'User', instance_name: 'user'
since the name of my model is user. Is there any way I can do it?
I have tried simply adding this line in ParticipantsController
but it gives me an NameError (uninitialized constant Participant)
. My guess it it still runs the load_and_authorize_resource
of the parent class.
I have tried using skip_load_and_authorize_resource
before it but it skips the loading and authorizing altogether i.e my @user object is nil.
Is there a solution to it?
Parent Class
module Api
module Cp
class CpController < Api::ApiController
load_and_authorize_resource
end
end
end
Child Class
module Api
module Cp
class ParticipantsController < Api::Cp::CpController
load_and_authorize_resource class: 'User', instance_name: 'user'
def show
@user
end
end
end
end
load_and_authorize_resource
is actually just a helper method that adds a before_action :load_and_authorize_resource
with additional args
to the controller.
That means, you can remove the inherited before_action
and then add your new version, like this:
module Api
module Cp
class ParticipantsController < Api::Cp::CpController
skip_before_action :load_and_authorize_resource
load_and_authorize_resource class: 'User', instance_name: 'user'
# ...