RobertJoseph
RobertJoseph

Reputation: 8158

CanCanCan gem: load_and_authorize_resource and a controller's index action

class TopicsController < ApplicationController
  load_and_authorize_resource # CanCanCan gem

  def index
    # @topics = Topic.visible_to(current_user)
  end
...
end

It is my understanding that load_and_authorize_resource loads up the necessary model instance for CRUD actions. Does that not include the controller#index action (where the instance variable is plural - in my case @topics)?

This doesn't work for me unless I uncomment the line in my index action.

Upvotes: 1

Views: 5728

Answers (2)

Feuda
Feuda

Reputation: 2375

index action

As of 1.4 the index action will load the collection resource using accessible_by.

def index
  # @products automatically set to Product.accessible_by(current_ability)
end

via https://github.com/ryanb/cancan/wiki/authorizing-controller-actions#load_resource

Upvotes: 1

eirikir
eirikir

Reputation: 3842

CanCanCan does load the instance variable for the index action starting in version 1.4 if using a supported ORM (including ActiveRecord) and defining your abilities without blocks.

In previous versions, load_and_authorize_resource only loads the singular instance variable for those routes with an :id parameter, i.e. the CRUD actions, as you noted. It does, however, authorize for all actions, but since it doesn't load an instance variable for the index action, it only authorizes based on the model. This means that it ignores any conditions placed in the ability for that model.

Upvotes: 2

Related Questions