You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When specifying numeric parameters, strong params lets you permit them all using the same permitted params for each.
For example params like,
```ruby
book: {
authors_attributes: {
'0': { name: "William Shakespeare", age_of_death: "52" },
'1': { name: "Unattributed Assistant" },
'2': "Not a hash",
'new_record': { name: "Some name" }
}
}
```
can be permitted with,
```
permit book: { authors_attributes: [ :name ] }
```
This returns the name keys for each of the numeric keyed params that have a name field,
```ruby
{ "book" => { "authors_attributes" => { "0" => { "name" => "William Shakespeare" }, "1" => { "name" => "Unattributed Assistant" } } } }
```
This is exactly what you want most of the time. Rarely you might need
to specify different keys for particular numeric attributes. This
allows another strong params syntax for those cases where you can
specify the keys allowed for each individual numerically keys attributes
hash.
After this change using the same params above, you can permit the name and age for only the `0` key and only the name for the `1` key,
```ruby
permit book: { authors_attributes: { '1': [ :name ], '0': [ :name, :age_of_death ] } }
```
This returns exactly the parameters that you specify,
```ruby
{ "book" => { "authors_attributes" => { "0" => { "name" => "William Shakespeare", "age_of_death" => "52" }, "1" => { "name" => "Unattributed Assistant" } } } }
```
Sidenote: this allows `permit` to do the equivalent to
```ruby
params.require(:book).permit(authors_attributes: { '1': [:name]})
```
without raising when `book: ... ` is not present.
The simpler syntax should be preferred, but in cases where you need more control, this is a nice option to have.
0 commit comments