6

I have an array of objects being passed to my controller with this structure:

[
    {
        "id": 1,
        "fruit_ids": [1, 2, 3]
    },
    {
        "id": 2,
        "fruit_ids": [4, 5, 6]
    },
]

The root object, is not a {}, and instead is a array. I'm not sure how to write a strong params state for this case. I have tried

params.permit [:id, fruit_ids: []]

and other similar options, but it wasn't permitting it.

Edit:

I'm not sending a JSON object in my request body. I'm sending a JSON array. When I inspect the value of params in my controller, this is the result:

{
    "_json" => [
        {"id"=>1, "fruit_ids"=>[1, 2, 3]},
        {"id"=>2, "fruit_ids"=>[4, 5, 6]}
    ],
    "format"=>"json",
    "controller"=>"...",
    "action"=>"..."
}
2

2 Answers 2

5

This is the correct answer:

params.require(:_json).map { |params| params.permit(:id, :fruit_ids) }
Sign up to request clarification or add additional context in comments.

1 Comment

This is an excellent solution. thanks Pere Joan Martorell.
2

Ideally you should always send a JSON objects as a param, when you don't explicitly give a key for object, it takes _json as is the case with your params.

Anyway to write a strong parameter in your case, you can do something like,

params = ActionController::Parameters.new({
    "_json" => [
        {"id"=>1, "fruit_ids"=>[1, 2, 3]},
        {"id"=>2, "fruit_ids"=>[4, 5, 6]}
    ],
    "format"=>"json",
    "controller"=>"...",
    "action"=>"..."
}

params.permit('_json': [:id, fruit_ids: []]) # You need this line.

# => {"_json"=>[{"id"=>1, "fruit_ids"=>[1, 2, 3]}, {"id"=>2, "fruit_ids"=>[4, 5, 6]}]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.