CanCan difference between :read and [:index, :show]?
Asked Answered
M

1

10

According to all documentation, the :read action is aliased to both :index and :show:

alias_action :index, show, :to => :read

However, consider the following scenario with nested resources:

resources :posts
  resources :comments
end

If I define abilities like this:

# ability.rb
can :read, Post
can :show, Comment

# comments_controller.rb
load_and_authorize_resource :organization, :find_by => :permalink
load_and_authorize_resource :membership, :through => :organization

things work as expected. However, if I change the :read action to [:index, :show]:

# ability.rb
can [:index, :show], Post
can :show, Comment

# comments_controller.rb
load_and_authorize_resource :organization, :find_by => :permalink
load_and_authorize_resource :membership, :through => :organization

I am unauthorized to access /posts/:post_id/comments, /posts/:post_id/comments/:id, etc. I still, however, can access both :index and :show for the posts_controller.

How is possible that these actions are "aliased", if they behave differently?

In my fiddling, I also came across the following. Changing load_and_authorize_resource to the following allowed access:

# ability.rb
can [:index, :show], Post
can :show, Comment

# comments_controller.rb
load__resource :organization, :find_by => :permalink
load_and_authorize_resource :membership, :through => :organization

Can someone explain what's going on here?

Motoneuron answered 12/3, 2011 at 5:30 Comment(0)
M
16

I posted this as an issue on GitHub. Ryan responded with the following:

Both the :index and :show actions point to the :read action. But when CanCan authorizes a parent resource it uses the :read action directly which is why you're seeing this behavior.

I think this has caused confusion before, so I will change the internal behavior to never use the :read action directly. Instead of a :parent resource I'll change it to use :show and for the accessible_by default I will use :index instead of :read. Thanks for bringing this to my attention.

https://github.com/ryanb/cancan/issues/302#comment_863142

Motoneuron answered 12/3, 2011 at 6:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.