'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 1:[1]
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'
Solution 2:[2]
Q1. For UsersController it will be @user
Q2. If you have a right routes you can use
load_and_authorize_resource :custom_model_name
Also, it will be useful for you https://github.com/CanCanCommunity/cancancan
Solution 3:[3]
Q.1 > in your example it will be @user/@users
Q.2 > use the instance_name attribute, e.g. to load @object do
load_and_authorize_resource instance_name: :object
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | roarfromror |
| Solution 2 | AlexMrKlim |
| Solution 3 | Ed Posnak |
