ruby-on-rails-4ruby-2.1

custom instance variable name in cancan's load_and_authorize_resource?


users_controller.rb

class UsersController < ApplicationController  
  def index
    @objects = User.filter(params: params)
  end
end  

Q.1 > If 'load_and_authorize_resource' is called then what instance variable it will load ?
Q.2 > If it loads @user or @users then how to make it load on @object ?

I think I'm lacking sufficient knowledge understanding cancan (i'm a rails newbie) and using it since last 4 days, hoping this question makes sense.


Solution

  • A resource is not loaded if the instance variable is already set. This makes it easy to override the behavior through a before_filter on certain actions - from cancan https://github.com/ryanb/cancan/blob/master/lib/cancan/controller_additions.rb line 34 and 35, so you can do like this in your controller --

    before_filter :set_instance_variable  
    load_and_authorize_resource  
    private  
      def set_instance_variable
        @object = "blah blah blah"  
      end  
    

    load_and_authorize_resource should be called after setting instance variable i.e. after 'before_filter :set_instance_variable'