I have an api with the following POST route /carros
in the controller I have:
app/controllers/api/v1/cars_controller.rb
module API
module V1
class CarrosController < ApplicationController
skip_before_action :verify_authenticity_token
def create
@carro = Carro.new
@carro.marca = 'chevrolet'
@carro.modelo = 'impala'
@carro.color = 'azul'
@carro.save
end
end
end
end
In the view I have the following jbuilder:
app/views/api/v1/cars/create.json.jbuilder
json.ok true
json.carro do
json.marca @carro.marca
json.modelo @carro.modelo
json.color @carro.color
end
The cart is generated fine, with all its validations and the output jbuilder
also without problems, but a parameter may be missing in the header and result in a 406 Not Acceptable response , even with this response it still creates the cart, what I want is How do so that if there is a response 4xx 0 500 it does not create the cart?.
I have the doubt that your 406 is due to lack of a parameter. In general, this is usually a 422 and it is a status added by the programmer as a response, not returned by the framework.
To resolve a 406, I think you should define the valid response formats. There are several ways, one is by defining the format for your specific action:
another, defining the format of your entire controller:
and the last one is to set it to
config/routes.rb
:Regarding how to make the car not believe you with a 4xx or 5xx, that is one of the great dilemmas of web programming, haha. Unfortunately, there is no absolute solution and you have to approach it on a case-by-case basis, since you cannot anticipate where the next error will be generated. For example, you could include in the action all the creation of your cart together with other accesses to the DB within the same SQL transaction, it processed everything ok, but in the view you have an error and it will return 500 anyway having created the carriage... and that's fine, because your error is in the view, not the controller, so there's no reason to rollback that either. In fact, the request could have passed everything fine, generate the view fine, then rails delegates the response to your nginx server, but this has a problem and will return 500 anyway...