【问题标题】:CanCan: Load and Authorize some resources in a Controllers without modelsCanCan:在没有模型的控制器中加载和授权一些资源
【发布时间】:2016-09-21 09:27:55
【问题描述】:

我有一个没有模型的控制器。在这个控制器中,我们正在加载一些其他资源。最重要的是,该应用程序具有多租户功能。

代码如下:

# ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    if user.owner?
      can :manage, Tool, tenant_id: user.tenant.id
    end
  end
end

# boxes_controller.rb
class BoxesController < ApplicationController
  authorize_resource class: false

  def index
    tools = Tool.all
  end
end

有什么问题?:

比如说,tenant1user1 创建 tool1tenant2user2 创建 tool2

问题是,从tenant1user1可以访问tool2! :(

我写错了吗?请帮忙。

【问题讨论】:

    标签: ruby-on-rails multi-tenant cancan cancancan


    【解决方案1】:

    试试这个

    if user.owner?
      can :manage, Tool do |tools|
        tools.tenant_id == user.tenant.id
      end
    end
    

    在控制器中

    authorize_resource class: false
    

    希望有帮助!

    【讨论】:

    • 非常感谢您的回答。我已经尝试过了,但没有运气:(,它不起作用。
    【解决方案2】:

    “不完全阅读 gem 的文档”真的是我的坏习惯。我在这里找到了解决方案:https://github.com/ryanb/cancan/wiki/Fetching-Records

    # ability.rb
    class Ability
      include CanCan::Ability
    
      def initialize(user)
        if user.owner?
          can :manage, Tool, tenant_id: user.tenant.id
        end
      end
    end
    
    # boxes_controller.rb
    class BoxesController < ApplicationController
      authorize_resource class: false
      before_action :set_tool, only: %i(edit update destroy)
    
      def index
        tools = Tool.accessible_by(current_ability)
      end
    
      private
    
      def set_tool
        @tool = Tool.find params[:id]
        authorize! :manage, @tool
      end
    end
    

    也许它会对某人有所帮助。谢谢!

    【讨论】:

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