【问题标题】:CanCan - Undefined method find for specific classCanCan - 查找特定类的未定义方法
【发布时间】:2011-12-17 18:43:10
【问题描述】:

我有一个名为 Administrator 的控制器。这个控制器对其他模型有动作。当我尝试使用 CanCan 授权此操作时,我收到此响应。

<h1>
  NoMethodError
    in AdministratorController#preproduct_delete
</h1>
<pre>undefined method `find' for Administrator:Class</pre>

控制器代码以:

开头
class AdministratorController < ApplicationController

  load_and_authorize_resource
  before_filter :authenticate_user!

  def users
    authorize! :users, "Users List"
    @users = User.all
  end

end

能力模型有:

if user.admin? then :admin
    can :users
end

authenticate_user! 方法:

# See ControllerAdditions#authorize! for documentation. 
def authorize!(action, subject, *args) 
  message = nil 
  if args.last.kind_of?(Hash) && args.last.has_key?(:message) 
    message = args.pop[:message] 
  end 
  if cannot?(action, subject, *args) 
    message ||= unauthorized_message(action, subject) 
    raise AccessDenied.new(message, action, subject) 
  end 
  subject 
end 

我试图从控制器中删除 load_and_authorize_resource,但是当调用任何操作时,CanCan 每次都会将我重定向到登录页面。

非常感谢

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    你没有指定权限,can :user 是什么意思?指定一个权限,所有权限使用 :manage。

    if user.admin?
        can :manage, :users
    end
    

    【讨论】:

    • 是的,我尝试使用 can :manage, :all 并获得相同的结果。谢谢
    【解决方案2】:
    <h1>
      NoMethodError
        in AdministratorController#preproduct_delete
    </h1>
    

    请粘贴AdministratorController的preproduct_delete

    <pre>undefined method `find' for Administrator:Class</pre>
    

    管理员是否从 ActiveRecord::Base 继承?如果它没有找到是因为没有。 应该是

    class Administrator < ActiveRecord::Base
    

    authenticate_user! 方法:

    # See ControllerAdditions#authorize! for documentation. 
    def authorize!(action, subject, *args) 
     ....
    end   
    

    这不是authenticate_user!方法,这是授权! 非常不同,你有 before_filter authenticate_user!在此处发布此方法。有些东西正在调用 preproduct_delete。

    【讨论】:

    • 我做了一些测试,问题是 CanCan gem 想要检查方法的权限。我想可能是因为我有一个控制器(管理员)使用不同的模型,如 Preproduct、Product 等。
    【解决方案3】:

    一个可能的原因是需要明确设置类名。在我的示例中,我将 cmets 资源嵌套在线程资源下,并且我在控制器中编写了以下内容:

    class Buy::CommentsController < ApplicationController
      load_and_authorize_resource :thread
    

    这给了我undefined find method 错误,因为注释模型位于线程命名空间下。当我像下面这样明确设置它时,它可以工作。

    class Buy::CommentsController < ApplicationController
      load_and_authorize_resource :thread, class: Buy::Thread
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 2022-12-23
      相关资源
      最近更新 更多