The parameters I received in Rails were a bit different than I expected

API mode.

When I used axios to POST the action while using Rails as an API, I received it as params in a different form than I expected on the Rails side.

front.ts


  axios.post('/api/v1/users', {id: user.id})

back.rb


class Api::V1::UsersController < ApplicationController
  def index
  end
end

The value sent was expected to be {" id "=> 1},

Looking at the log, it was {" id "=> 1," user "=> {" id "=> 1}}.

This seems to be a specification on the Rails side.

Similarly, if you turn on config.wrap_parameters in your initialization settings, or if your controller calls wrap_parameters, you can safely remove the root element of the JSON parameter. By default, this parameter is then duplicated and wrapped with a key name that corresponds to the controller name. Therefore, the JSON request above can be written as: { "name": "acme", "address": "123 Carrot Street" } If the data is sent to CompaniesController, it will be wrapped with the key: company as shown below. { name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }

Rails in API mode is now initializer

wrap_parameters.rb


ActiveSupport.on_load(:action_controller) { wrap_parameters format: %i[json] }

It seems that this is working because there is.

However, this does not happen with a GET request.

Recommended Posts

The parameters I received in Rails were a bit different than I expected
[Rails] I want to send data of different models in a form
I tried to organize the session in Rails
(Capistrano) After deploying, I get a We're sorry… error in the production environment.
[Rails] I want to display the link destination of link_to in a separate tab
I want to use a little icon in Rails
[Ruby / Rails] Set a unique (unique) value in the class
I want to define a function in Rails Console
I want to create a form to select the [Rails] category
A story I was addicted to in Rails validation settings
I came across a guy with two dots in Rails
I was confused because there was a split in the Array
[Learning record] I got the current time in Ruby and output a different greeting for each time.
What if I write a finally clause in the try-with-resources syntax?
I tried to illuminate the Christmas tree in a life game
I tried to sort the data in descending order, ascending order / Rails
I made a reply function for the Rails Tutorial extension (Part 1)
I recently made a js app in the rumored Dart language
I got a warning message with the rails _6.0.3_ new hello_myapp command
I made a reply function for the Rails Tutorial extension (Part 5):
Install Rails in the development environment and create a new application
I don't see an error in Rails bundle install ... the solution
I summarized the flow until implementing simple_calendar in Ruby on Rails.