Search code examples
ruby-on-railsauthorizationcancancancancan

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.


Solution

  • 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.