【问题标题】:How to get a list of permitted params for a specific controller action如何获取特定控制器操作的允许参数列表
【发布时间】:2016-10-07 18:07:28
【问题描述】:

问题的标题几乎描述了我需要做什么。和这个问题基本一样,一直没有得到答案:

Rails 4: get list of permitted attributes (strong parameters) from a controller

与该问题中提供的示例类似,如果存在,它将等同于这样的内容:

account_update_permitted_params = AccountController.permitted_params(:update)

【问题讨论】:

    标签: ruby-on-rails-4 controller strong-parameters


    【解决方案1】:

    由于强参数的性质,您基本上不能这样做。

    您在some_resource_attributes 中定义的内容是为了过滤请求的参数哈希。如果您查看方法定义,您将看到 params.require(:some_resource).permit.. - 它对 params 对象进行操作,该对象仅在请求期间存在。

    所以有这样的方法似乎用处不大。

    如果您真的想以编程方式访问 some_resource_attributes 中的白名单属性,您可以使用:

    class ResourceController < ApplicationController
      LIST = %i(foo bar baz)
    
      private
    
      def resource_attributes
        params.require(:resource).permit(*LIST)
      end
    end
    ResourceController::LIST
    #=> [:foo, :bar, :baz]
    

    但我确实看到了这一点,因为您可以打开控制器的代码并检查它。

    【讨论】:

    • 感谢您的回复!我试图以编程方式访问无法添加其他代码的控制器的允许属性,例如您的示例中的LIST。我看到这是不可能的,因为正如您所说,params 对象仅在请求期间存在。
    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2015-06-24
    相关资源
    最近更新 更多