Home > Mobile >  Is there an implied top level parameter that is required when using rails
Is there an implied top level parameter that is required when using rails

Time:04-18

Im trying to understand how parameters require work with rails controllers. I have a user controller to create a user. My json looks like so:

{
"name":"user onex",
"username":"useronea",
"email":"[email protected]",
"password":"123456",
"password_confirmation":"123456"
}

And my controller code looks like this

# POST /users
def create
  @user = User.new(user_params)
  if @user.save
    render json: @user, status: :created
  else
    render json: { errors: @user.errors.full_messages },
           status: :unprocessable_entity
  end
end
def user_params
  params.permit(
    :name, :username, :email, :password, :password_confirmation
  )
end

rails lets me create this user but I do see an error in red stating

Unpermitted parameter: user

If I modify the user_params as follows (Like I've seen on other examples)

  params.require(:user),permit(
    :name, :username, :email, :password, :password_confirmation
  )

The rails application fails to see my email and password. I get a 403 error

I don't understand why I'm getting the unpermitted parameter 'user' when Im not sending that parameter in the first case unless its just implied. If its implied then why doesn't the second case work.

CodePudding user response:

Yes, there is.

Also, if you've turned on config.wrap_parameters in your initializer or called wrap_parameters in your controller, you can safely omit the root element in the JSON parameter. In this case, the parameters will be cloned and wrapped with a key chosen based on your controller's name.

ActionController::ParamsWrapper will turn:

{ "name": "acme", "address": "123 Carrot Street" }

Into:

{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }

The idea is that you can use the same params whitelisting method for both flat JSON parameters and nested FormData parameters when you have controllers that serve both JSON and HTML.

You can disable it with for your entire application with config.wrap_parameters = false or per controller with the wrap_parameters false class method.

CodePudding user response:

Beetween the lines:

def create
    @user = User.new(user_params)

put debugger.

After running rails server, the execution stops in debugger, so at that moment you may see params json format.

  • Related