嵌套哈希的强参数

时间:2015-09-24 16:25:24

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

我有以下参数,无法获得强大的参数。

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

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

params = ActionController::Parameters.new(json)

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

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

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

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

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

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

2 个答案:

答案 0 :(得分:5)

使用如下语法完成:

answers_attributes: [:id, :content]

问题是您在answers_attributes中使用的密钥。它们应该是answers_attributes的ID或新记录0的ID。

更改这些会给出您的预期结果:

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,似乎使用了很长的随机数。

答案 1 :(得分:1)

您的answers_attributes包含不允许的c1和c2。 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

方式1:您可以将嵌套属性作为哈希数组传递。

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

现在params.permit(:id, answers_attributes: [:id, :content])给出了

{"id"=>1, "answers_attributes"=>[{"id"=>"", "content"=>"Hi"}, {"id"=>"", "content"=>"Ho"}]}

方式2:您可以像哈希一样传递哈希值

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

WAY 1 WAY 2 在模型级别中具有相同的效果。但是permit不允许值通过,除非明确指定了键。因此,除非明确指定为

,否则不允许c1c2
params.permit(:id, answers_attributes: [c1: [:id, :content], c2: [:id, :content]])

这真是一个痛苦的屁股。

相关问题