In the case where the controller and Ability target are different, such as DashboardController, in the CANCAN gem, it does not work, and it becomes an uninitialized constant Dashboard.

Asked 2 years ago, Updated 2 years ago, 46 views


in a Dashboard Controller, where you want to view a list of users, etc. uninitialized constant dashboard
The error appears.

I'd like to make the cancellation work even if the controller and Ability target are different.
I'm having a hard time because I don't know what to do.


class DashboardController
  load_and_authorize_resource(1)
  # skip_load_and_authorize_resource(2)
  # load_and_authorize_resource:user, :parent=>false(3)

  @users=current_user(4)

end

(1) If this is the case, the following error will be displayed:
uninitialized constant dashboard

(2) This eliminates errors, but does not serve the purpose because permission management is not possible.

(3) When I looked into it, it was written that I could do it this way, but it didn't work under my environment.
https://github.com/CanCanCommunity/cancancan/wiki/Authorizing-controller-actions#custom-class

(4) In the case of Admin, I want User.all, otherwise I want to get current_user.

I've made my own authority check, but
With this method, the (4) part is not working well, and we are having difficulty with this way.
http://qiita.com/snaka/items/2f30e6abedf7f7a33e99

Thank you for your cooperation.

ruby-on-rails ruby

2022-09-30 17:30

1 Answers

I think the answer to (3) will be helpful.This time you used the first one on the referenced site, but please try the second option.

If the model class is named differently than the controller you will need to specify the:class option.

Roughly translated,

If the controller and class names are different, you must use the :class option.

Therefore, using the class option, I think you can write as follows.

class ProductsController<ApplicationController
  load_and_authorize_resource class: "User"
end

When I tried, there was a misunderstanding in the variable name, so I will add it.

class DashboardController
  load_and_authorize_resource class: "User"

  def index   
    Rails.logger.debug@users#=>nil
    [email protected]_sql#=>SELECT "users".* FROM "users"
  end  
end

It was stored in the variable name of the controller name, not the class name you are referring to.
You may want to try copying the above.
(By any chance, is there no def index?)


2022-09-30 17:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.