Skip to content

Commit 43e2e80

Browse files
committed
Merge pull request #19 from tomfwz/strong-parameters-with-array
TIL Rails: Strong parameters with array
2 parents 2dedc71 + 3989442 commit 43e2e80

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

rails/strong-parameters-with-array.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
By default, strong parameter just permit parameter with values are string.
2+
3+
```ruby
4+
"category"=>{"options_attributes"=>{"0"=>{"value"=>["FSE", "FDI"], "id"=>"61"}, "1"=>{"value"=>"14", "id"=>"62"}, "2"=>{"value"=>"10", "id"=>"63"}}}
5+
6+
params.require(:category).permit(options_attributes: [:id, :value])
7+
8+
{"options_attributes"=>{"0"=>{"id"=>"61"}, "1"=>{"id"=>"62", "value"=>"14"}, "2"=>{"id"=>"63", "value"=>"10"}}}
9+
```
10+
11+
If you need to permit parameter with values are an array. Let's use:
12+
13+
```ruby
14+
params.require(:category).permit(options_attributes: [:id, value: []])
15+
16+
{"options_attributes"=>{"0"=>{"id"=>"61", "value"=>["FSE", "FDI"]}, "1"=>{"id"=>"62"}, "2"=>{"id"=>"63"}}}
17+
```
18+
19+
But the string values are cleared out, so in case you need to permit both of string values and array values. Let's use simple trick:
20+
21+
```ruby
22+
params.require(:category).permit(options_attributes: [:id, :value, value: []])
23+
24+
{"options_attributes"=>{"0"=>{"id"=>"61", "value"=>["FSE", "FDI"]}, "1"=>{"id"=>"62", "value"=>"14"}, "2"=>{"id"=>"63", "value"=>"10"}}}
25+
```

0 commit comments

Comments
 (0)