具有嵌套散列的强参数

具有嵌套散列的强参数

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

问题描述

我有以下参数,但无法使用强参数.

I have the following params and cannot get the strong parameters to work.

这是我的基本代码,为了简单起见,可以在 Rails 控制台中运行:

Here's my basic code, runnable in the Rails console for simplicity:

json = {
  id: 1,
  answers_attributes: {
    c1: { id: "", content: "Hi" },
    c2: { id: "", content: "Ho" }
  }
}

params = ActionController::Parameters.new(json)

我读过的所有内容都说以下应该有效,但它只给我 idanswers_attributes 的空哈希:

Everything I've read says the following should work, but it only gives me the id and an empty hash of answers_attributes:

params.permit(:id, answers_attributes: [:id, :content])
=> { "id"=>1, "answers_attributes"=>{} }

如果我改为手动列出 c1c2(如下所示)它可以工作,但这真的很愚蠢,因为我不知道用户会提供多少答案,这是很多重复:

If I instead manually list c1 and c2 (like below) it works, but this is really stupid because I don't know how many answers the user will supply, and this is a lot of duplication:

params.permit(:id, answers_attributes: { c1: [:id, :content], c2: [:id, :content] })
=> {"id"=>1, "answers_attributes"=>{"c1"=>{"id"=>"", "content"=>"Hi"}, "c2"=>{"id"=>"", "content"=>"Ho"}}}

我已经尝试用 01 替换 c1c2,但我仍然需要手动在我的许可声明中提供 01.

I've tried replacing c1 and c2 with 0 and 1, but I still have to manually supply the 0 and 1 in my permit statement.

如何允许未知长度的嵌套属性数组?

How can I permit an unknown length array of nested attributes?

推荐答案

它的语法如下:

answers_attributes: [:id, :content]

问题在于您在 answers_attributes 中使用的键.它们应该是 answers_attributes 的 id,或者在新记录 0 的情况下.

The problem is the keys you are using in the answers_attributes. They are expected to be the ids of the answers_attributes or in the case of new records 0.

改变这些会给你预期的结果:

Changing these gives your expected outcome:

json = {
  id: 1,
  answers_attributes: {
    "1": { id: "", content: "Hi" },
    "2": { id: "", content: "Ho" }
  }
}

params = ActionController::Parameters.new(json)

params.permit(:id, answers_attributes:[:id, :content])
=>  {"id"=>1, "answers_attributes"=>{"1"=>{"id"=>"", "content"=>"Hi"}, "2"=>{"id"=>"", "content"=>"Ho"}}}

看来 0 不是唯一的键,我的意思是如果您有两个 new 记录怎么办.我使用 nested_form 并且它似乎使用了一个很长的随机数.

It appears that 0 is not the only key, I mean what if you have two new records. I use nested_form and it appears to use a very long random number.

这篇关于具有嵌套散列的强参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:23