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