CanCan: load_and_authorize_resource in a namespace other than the MainApp namespace

I use CanCan for permissions in my Rails application, in which I created my own engine for some common form functions. I would like to block access rights in my system so that users cannot freely access the actions of my controllers. These controllers, for the most part, simply use 7 REST actions, so I would like to use the CanCan load_and_authorize_resource at the top of each controller.

However, when I write my code as follows:

  module MyEngine class FormController < ApplicationController load_and_authorize_resource ... end end 

I get this error:

  uninitialized constant Form 

I assume that the automatic loader in load_and_authorize_resource bound to my MainApp namespace and does not recognize that I am calling it in a different namespace, but also a call like Form.find(params[:id]) , not MyEngine::Form.find(params[:id]) .

If so, how can I fix it? This is not a huge deal because authorize! it still works correctly, so I can define authorization in each action individually, but it would be much cleaner if I could use the load_and_authorize_resource method.

+6
source share
3 answers

It seems that the error in CanCan::ControllerResource#namespace :

 def namespace @params[:controller].split("::")[0..-2] end 

As you can see, it tries to split the controller path into :: , but it comes in the form my_engine/my_controller .

So, the unwashed fix is ​​simple:

 def namespace @params[:controller].split("/")[0..-2] end 

I wonder how they could have missed such a stupid mistake for so long. Send them a transfer request.

PS Just signed up to answer 8)

+6
source

CanCan cannot find models with names. Try specifying a class:

 load_and_authorize_resource class: MyEngine::Form 
+8
source

If the model class takes place with names other than the controller, you need to specify the parameter :class .

 module MyEngine class FormController < ApplicationController load_and_authorize_resource :class => MyEngine::Form ... end end 
+3
source

Source: https://habr.com/ru/post/922683/


All Articles