I realized recently that a parameter is added when I try to create multiple items of my class User in a POST request.
I have some permitted parameters:
def user_params
params.permit(:account_id, users: [:type, :name, :account_id])
end
Here is my create method in my UsersController
:
def create
if user_params[:users].blank?
render status: :no_content
return
end
begin
_users= User.create!(user_params[:users])
render json: _users, status: :created
rescue ActiveRecord::RecordInvalid
render json: _users.errors, status: :unprocessable_entity
end
end
When I try to test this using Postman, I use these parameters:
{
"users": [{
"type": "test",
"name": "test",
"account_id": "2DAC41seuRwGIxTn4PQPZc"
}, {
"type": "test2",
"name": "test2",
"account_id": "2DAC41seuRwGIxTn4PQPZc"
}]
}
Here is also the router conf:
resources :account, except: [:index] do
resources :users, only: [:create, :show, :index]
end
Each time I do a POST request on /accounts/2DAC41seuRwGIxTn4PQPZc/users
, I see in the rails console that the parameters are:
Parameters: {"users"=>[{"type"=>"test", "name"=>"test", "account_id"=>"2DAC41seuRwGIxTn4PQPZc"}, {"type"=>"test2", "name"=>"test2", "account_id"=>"2DAC41seuRwGIxTn4PQPZc", }], "account_id"=>"2DAC41seuRwGIxTn4PQPZc", "user"=>{}}
Unpermitted parameter: :user.
I don't know where this parameter come from. Can someone enlighten me ?
Note that I'm still learning rails and ruby overall, maybe I'm missing something obvious.
As @spickerman mentioned it, the problem was that the ParamsWrapper was expecting a JSON format, and according to the doc:
If you enable ParamsWrapper for :json format, [...], it will be wrapped into a nested hash with the key name matching the controller's name.
However, even though the controller is plural, the model name has to be singular.
I fixed my problem changing users
list to user
:
{
"user": [{
"type": "test",
"name": "test",
"account_id": "2DAC41seuRwGIxTn4PQPZc"
}, {
"type": "test2",
"name": "test2",
"account_id": "2DAC41seuRwGIxTn4PQPZc"
}]
}
Parameters: {"user"=>[{"type"=>"test", "name"=>"test", "account_id"=>"2DAC41seuRwGIxTn4PQPZc"}, {"type"=>"test2", "name"=>"test2", "account_id"=>"2DAC41seuRwGIxTn4PQPZc", }], "account_id"=>"2DAC41seuRwGIxTn4PQPZc"}