I sent the following parameters to one users table to create multiple records at the same time.
Parameters: {"users"=>[{"name"}=>{"satoshi"}, {"name"}=>{"yuta"}]}
private
def users_params
params.require(:users).permit(
:id,
:name
)
end
If you use the permit method after require, I was told "** permit? I don't know such a method **".
.js
[1] pry(#<UsersController>)> params.require(:users).permit
NoMethodError: undefined method `permit'
for #<Array:0x00007f2024a3ee40>from (pry):62:in `users_params'
(The result of binding.pry is output)
Since params.require (: publisheds) is a ** Array class, the permit method cannot be used. ** **
.js
[2] pry(#<UsersController>)> params.require(:users).class
=> Array
[3] pry(#<UsersController>)> params.require(:users).respond_to?("permit")
=> false
.js
[4] pry(#<UsersController>)> params.require(:users)[0].respond_to?("permit")
=> true
[5] pry(#<UsersController>)> params.require(:users)[0].permit(:name)
=> <ActionController::Parameters {"name"=>"satoshi"} permitted: true>
If you come in an array, you should take them out one by one, right? I tought.
Turn with map, disassemble the array, permit and return
private
def users_params
params.require(:users).map do |user|
user.permit(
:id,
:name
)
end
end
The specification of = ruby that evaluates a block and has an array as a return value implicitly returns (returns) the last evaluated value.
I turn the array and take an argument, but even if I permit in it, it doesn't return a value? Is the permit method a little different because it is a permit rather than a value change (assignment)?
It's difficult to make small differences. .. .. If you have a ruby master, I would like to ask you a question.
specifications of each https://docs.ruby-lang.org/ja/latest/method/Array/i/each.html
map specifications https://docs.ruby-lang.org/ja/latest/class/Array.html#I_COLLECT
Recommended Posts