Levi
Levi

Reputation: 45

Cancan Authorizing Controller Action in Nested Resources

Using the load_and_authorize_resource in CanCan you can choose which actions are authorized by using :only or :except. i.e. load_and_authorize_resource :only => [:index, :show]

I would like to do the same thing in my nested resources but can’t get it to work.

I have a nested resource like:

class TasksController < ApplicationController
  load_and_authorize_resource :project
  load_and_authorize_resource :task, :through => :project
end

and have tried to this to restrict the “:click” action:

class TasksController < ApplicationController
  load_and_authorize_resource :project
  load_and_authorize_resource :task, :through => :project, :except => :click
end

But this doesn’t work. Any Ideas how to choose certain actions with nested resources?

Upvotes: 0

Views: 620

Answers (1)

Levi
Levi

Reputation: 45

As seen here.

To skip authorizations for an action on a nested controller skip_authorize_resource needs to be used in the following way.

class TasksController < ApplicationController
  load_and_authorize_resource :project
  load_and_authorize_resource :through => :project

  skip_authorize_resource :only => :click  
  skip_authorize_resource :project, :only => :click
end

The first skip_authorize_resource skips authorization check for task and the second for project. Both are needed if you want to skip all authorization checks for an action.

Upvotes: 3

Related Questions