【问题标题】:rails administrate with cancancanrails 用 cancancan 管理
【发布时间】:2018-11-10 11:39:29
【问题描述】:

我正在为我的应用程序使用 rails administrate,但我想通过管理仪表板限制对正在管理的资源的访问。

我还在我的 rails 应用程序的其他部分使用 cancancan 来管理访问和权限。

是否有人设法在 administrate 中使用 cancancan,以便管理仪表板可以使用 cancancan 中定义的功能、显示资源并应用相同的权限?

谢谢

【问题讨论】:

    标签: ruby-on-rails-5 cancancan administrate


    【解决方案1】:

    你可以在这里找到一些关于需要做什么的信息:https://administrate-prototype.herokuapp.com/authorization

    那里提到的内容对于过滤记录集合非常有效,但在尝试授权单个资源时会中断。解决方案是覆盖 find_resource 方法。这是最终的工作代码:

    # app/controllers/admin/application_controller.rb
    
    rescue_from CanCan::AccessDenied do |exception|
      flash[:notice] = "Access Denied"
      redirect_to admin_root_path
    end
    
    # Override find_resource, because it initially calls scoped_resource.find(param)
    # which breaks since we are overriding that method as well.
    def find_resource(param)
      resource_class.default_scoped.find(param)
    end
    
    # Limit the scope of the given resource
    def scoped_resource
      super.accessible_by(current_ability)
    end
    
    # Raise an exception if the user is not permitted to access this resource
    def authorize_resource(resource)
      raise CanCan::AccessDenied unless show_action?(params[:action], resource)
    end
    
    # Hide links to actions if the user is not allowed to do them      
    def show_action?(action, resource)
      # translate :show action to :read for cancan
      if ["show", :show].include?(action)
        action = :read
      end
      can? action, resource
    end
    

    这将使您开始使用CanCan 进行基本资源授权。如果您需要限制对嵌套资源等的访问,则可能需要进一步自定义字段视图。但从那时起,这应该是相当标准的。希望这可以帮助。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多