I’m migrating a Rails UJS / Turbolinks app to just Turbo and I came across the issue with form submission errors. Currently all of the controller actions looks something similar to this one:
def create @model = Model.new(model_params) if @model.save redirect_to edit_model_path(@model) else render :new end end
Which worked fine with Rails UJS / Turbolinks. When we submit a form and there are errors, the server responds with status 200, but an error message is displayed on the page.
Moving to Turbo, tho, this wont work. An error in the browser console is thrown when the controller tries to render the new page and respond with status 200:
Error: Form responses must redirect to another location
Searching for a way to fix my issue I came accross the following release and there it says:
CHANGED: Turbo now renders 4xx and 5xx HTML error responses to form submissions for both Turbo Drive and Turbo Frames. We suggest serving form validation errors with a HTTP 422 status. [#39]
Which makes sense, the server couldn’t create the object, hence a response with an error status code should be returned. This, however, means I have to change all of my controllers to:
def create @model = Model.new(model_params) if @model.save redirect_to edit_model_path(@model) else render :new, status: :unprocessable_entity end end
So my question is: Is this how it should be done? Do I have to go through all of those 30 controllers and set the status code or is there a easier way of doing it?