Strong parameters with nested hash

I have the following options and can't make strong options work.

Here is my basic code executed in the Rails console for simplicity:

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

params = ActionController::Parameters.new(json)

All I read says the following should work, but it only gives me idan empty hash answers_attributes:

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

If I instead manually list c1and c2(for example, below), this works, but it is really stupid, because I do not 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"}}}

I tried to replace c1, and c2on 0and 1, but I still have to manually specify 0and 1my permission instructions.

How to resolve an array of unknown lengths of nested attributes?

+4
2

:

answers_attributes: [:id, :content]

, answers_attributes. , answers_attributes 0.

:

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 , , .

+5

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 , . , c1 c2 ,

params.permit(:id, answers_attributes: [c1: [:id, :content], c2: [:id, :content]])

.

+1

Source: https://habr.com/ru/post/1608847/


All Articles