1

Below is my Ability file.

In most controllers, if I want to apply cancan, I just need to put load_and_authorize_resource in the beginning of the controller.

What if I want to make a specific controller called ABC, and not allow the user to run the index action (i.e. show)?

Any ideas?

class Ability
include CanCan::Ability

  def basic_read_only
    can :read, :all
    can :list, :all

    can :search, :all
  end

  def basic_operation
    can :read, :all
    can :list, :all
    # can :edit, :all
    can :create, :all
    can :search, :all
  end

  def initialize(user)

    if user.blank?
      # user.role == 'guest'
      cannot :manage, :all
      basic_read_only
    else
      if 'admin' == user.role
        can :manage, :all      
      else
        # cannot :manage, :all
        # basic_read_only
        basic_operation
      end
   end
    end

end   

2 Answers 2

0

You can ensure the authorization is specific to the action level as well with check_authorization.

~ ... application_controler.rb

class ApplicationController < ActionController::Base
  check_authorization
end

If you have not authorized user X (through ability.rb) to perform action index at your controler, it should work.

Another option is only include autorization in the index resource:

~ ... products_controler.rb

class UsersController < ActionController::Base

 def index
   @products = Product.all
   authorize! :read, @products
 end
end

By the way, when developping CanCan Ryan has used :read as an alias for both actions :show and :index (...alias_action :index, :show, :to => :read).

0

you can pass params to load_and_authorize_resource, ex:

load_and_authorize_resource :only => [:index, :show]

If you want to deny only index and show for class ABC

can :manage, ABC
cannot :read, ABC

I really recommend you to read the wiki it's very clear https://github.com/ryanb/cancan/wiki/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.