Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 741
sethvargo Avatar asked Mar 12 '11 05:03

sethvargo


1 Answers

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

like image 72
sethvargo Avatar answered Nov 05 '22 03:11

sethvargo