rjurado01
rjurado01

Reputation: 5535

Permitting nested arrays using strong params in Rails

How can I permit nested arrays using strong parameters?

ActionController::Parameters.new(filter: ['a', [1,2]]).permit(filter: [])
Unpermitted parameter: :filter

Expected output:

<ActionController::Parameters {"filter"=>["a", [1,2]]} permitted: true>

Upvotes: 0

Views: 2098

Answers (1)

Yakov
Yakov

Reputation: 3191

I believe the only way to work with nested parameters is to permit them as an array of hashes or use only scalar values inside the array.

According to the documentation:

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

You can also use permit on nested parameters, like:

params.permit(:name, {:emails => []}, :friends => [ :name, { :family => [ :name ], :hobbies => [] }])

Your case with flattened values:

> ActionController::Parameters.new(filter: ['a', 1,2]).permit(filter: [])
=> <ActionController::Parameters {"filter"=>["a", 1, 2]} permitted: true>

With an array of hashes:

> ActionController::Parameters.new(filter: [{param1: 'a', param2: [1,2]}]).permit(filter: [:param1, param2: []])
=> <ActionController::Parameters {"filter"=>[<ActionController::Parameters {"param1"=>"a", "param2"=>[1, 2]} permitted: true>]} permitted: true>

Upvotes: 3

Related Questions