中将深度嵌套的强参数列入白名单

中将深度嵌套的强参数列入白名单

本文介绍了在 Rails 中将深度嵌套的强参数列入白名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将序列化的 Ransack 搜索存储在文本列中.它是深深嵌套的,我正在努力为它提出许可要求.这是一个示例哈希:

I'm trying to store a serialized Ransack search in a text column. It's deeply nested and I'm struggling coming up with permit call for it. Here's a sample hash:

{
  "c"=>{
    "0"=>{
      "a"=>{
        "0"=>{
          "name"=>"column_1"
        }
      },
      "p"=>"eq",
      "v"=>{
        "0"=>{
          "value"=>"value_1"
        }
      }
    },
    "1"=>{
      "a"=>{
        "0"=>{
          "name"=>"column_2"
          }
      },
      "p"=>"cont",
      "v"=>{
        "0"=>{
          "value"=>"value_2"
        }
      }
    }
  }
}

你会怎么写许可证?这是我阅读文档的最佳猜测,但它不起作用.

How would you write a permit for that? This is my best guess for reading the doc but it isn't working.

def course_listing_params
  params.require(:course_listing).permit({ q: { c: [{ a: [:name] }, :p,  { v: [:value] }] } })
end

推荐答案

我最终构建了另一个模型来存储条件,并使用 accepts_nested_attributes_for 在 course_listing 控制器中创建所有条件.

I ended up building another model to store the conditions and using accepts_nested_attributes_for to create the conditions all within the course_listing controller.

我必须添加

conditions_attributes: [:id, :attr, :pred, :val, :_destroy]

我的许可电话,以使一切正常.中间三个是我自己的属性,:id 防止 Rails 在每次编辑时添加新条件,而 :_destroy 是为了删除条件.

to my permit call in order to make everything work. The middle three are my own attributes, the :id prevents Rails from adding new conditions with every edit, and the :_destroy is so you can delete conditions.

这篇关于在 Rails 中将深度嵌套的强参数列入白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:42