at.
at.

Reputation: 52580

How to allow users to view individual instances of a resource but not the index with CanCan?

I'll try to be more clear than the title. I want users to be able to view all individual widgets which might be at the following URLs:

/widgets/2
/widgets/3
/widgets/45

But I don't want users to view the entire index:

/widgets

I know I can check this in the controller or even in the view for index and show, but I'm looking for a simpler way I can add this in the Ability.rb file:

can :read, Widget

Of course, that will allow users to view the index too...

Upvotes: 1

Views: 59

Answers (2)

Jared Beck
Jared Beck

Reputation: 17538

I want users to be able to view all individual widgets .. but I don't want users to view the entire index

Use :show, not :read.

can :show, Widget

:read is an alias for [:show, :index].

Upvotes: 1

Rodrigo Zurek
Rodrigo Zurek

Reputation: 4575

Does it has to be with cancan? cause if not you can do a before filter on the index action on the controller like this:

controller

before_filter :check_user,  :only => [:index]  

def index
  // code
end

def check_user
 if current_user.type==1
  redirect to root_url
 end
end

ok how about this with cancan

ability.rb

cannot :manage, Widget

controller

skip_authorize_resource :only => :show

Upvotes: 0

Related Questions