【问题标题】:How to modify cancan load and authorize resource to load resource using different id如何修改cancan加载和授权资源以使用不同的id加载资源
【发布时间】:2023-07-28 23:33:01
【问题描述】:

如何修改加载和授权资源以使用不同的 id 加载资源。例如。

我的路线是

http://localhost:3000/organization/user/12/event/20/edit

在我的事件控制器中,我使用:event_id 访问事件,用户使用:id 访问事件

现在在我的事件控制器中如何修改 load_and_authorize_resource 使用 :event_id 而不是 :id 来加载事件

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 cancan cancancan


    【解决方案1】:

    只有在尚未加载的情况下,资源才会加载到实例变量中。这使您可以轻松地在单独的 before_filter 中覆盖加载方式。

    class EventsController < ApplicationController
      before_filter :find_event
      load_and_authorize_resource
    
      private
    
      def find_event
        @event = Event.find(params[:event_id])
      end
    end
    

    在文档中阅读更多信息:https://github.com/CanCanCommunity/cancancan/wiki/Authorizing-controller-actions

    【讨论】:

      【解决方案2】:

      CanCan 通过id_param 选项支持这一点:

      来自documentation

        # [:+id_param+]
        #   Find using a param key other than :id. For example:
        #
        #   load_resource :id_param => :url # will use find(params[:url])
      

      因此,您可以在您的情况下执行以下操作:

      load_and_authorize_resource :id_param => :event_id
      

      【讨论】:

      • +1。如果你想有选择地使用不同的列,比如几个继承的类使用不同的 id,那么有 prepend 选项 amitpatel.xyz/…
      最近更新 更多