skip to content

In a Rails controller, why does a failed save re-render the form with render :new, status: :unprocessable_content instead of redirecting?

level: juniorimportance: must knowfreq 70%

answer

  1. errors live on @volunteer
  2. a redirect starts a fresh request
  3. render skips the new action
  4. 422 is :unprocessable_content
  5. Turbo Drive needs a 4xx or a redirect

basics

~20 s

The errors and the typed input exist only on @volunteer in this request, so the action renders the form again from it. Status 422, :unprocessable_content, marks the failure, which Turbo Drive needs to display it.

solid answer

~40 s

When `@volunteer.save` returns false, the in-memory object still holds what the user typed and `@volunteer.errors`. `render :new` builds the form from that same object, so fields keep their input and the messages can be shown. `redirect_to new_volunteer_path` would start a new request with a new, empty object and lose both. The status matters because `render` defaults to 200: Turbo Drive treats a form submission answered 200 without a redirect as an error and leaves the page unchanged, while a 4xx response is rendered. Rails 8.1's scaffold therefore writes `render :new, status: :unprocessable_content` in `create` and `render :edit, ...` in `update`. `:unprocessable_content` is the Rack 3.1+ name for 422; `:unprocessable_entity` still maps to 422 but Rack prints a deprecation warning. Note that `render :new` only renders the template; it does not run the `new` action.

code

ruby · 20 lines
ruby
class VolunteersController < ApplicationController
  def new
    @volunteer = Volunteer.new
  end

  def create
    @volunteer = Volunteer.new(volunteer_params)

    if @volunteer.save
      redirect_to @volunteer, notice: "Thanks for signing up."
    else
      render :new, status: :unprocessable_content
    end
  end

  private
    def volunteer_params
      params.expect(volunteer: [:name, :email, :team_id])
    end
end

go deeper

for a junior

Recall the scaffold pattern: redirect when save succeeds, render :new with status :unprocessable_content when it fails, so the errors and typed values stay visible.

for a middle

Explain that errors live on the in-memory object, that render does not call the new action, and why the status decides whether Turbo Drive shows the response.

for a senior

Spot the production variants: missing statuses that fail only under Turbo, failure branches that re-fetch the record, and templates that need data the render path never loaded.

for a principal

Set the convention, failure renders with 422 and success redirects with 303 where needed, in generators and reviews so every form behaves the same under Turbo.

## Two outcomes, two responses A Rails form submission ends in one of two ways, and the generated scaffold shows both: | Outcome | Controller code | Response | |---|---|---| | saved | `redirect_to @volunteer, notice: "Thanks for signing up."` | 302 (303 for update and destroy) to the new page | | rejected | `render :new, status: :unprocessable_content` | 422 with the form HTML | The success path redirects so a reload does not post again. The failure path deliberately does not. ## Why the failure path renders - **The errors live on the object.** `save` runs validations and fills `@volunteer.errors`. That object exists only in this request's controller instance. - **The input lives on the object too.** Every attribute the user typed was assigned to `@volunteer`, so form helpers bound to it print those values back. - **A redirect throws both away.** `redirect_to new_volunteer_path` ends the request; the browser asks for `/volunteers/new`, and the `new` action builds an empty `Volunteer`. The user sees a blank form with no explanation. ## Why the status matters `render` answers 200 unless told otherwise. Three things depend on the 422: 1. **Turbo Drive.** For a non-GET form submission, Turbo renders a 4xx or 5xx response, or follows a redirect. A 200 without a redirect is reported as an error in the browser console and the page does not change, so the user never sees the errors. (Turbo's own rules belong to the Turbo Drive leaf.) 2. **Tests.** `assert_response :unprocessable_content` in a controller or integration test checks that the failure path really failed. 3. **Logs and monitoring.** A 422 line in the request log separates rejected input from successful pages. ## The status name in Rails 8.1 Rack renamed 422 from "Unprocessable Entity" to "Unprocessable Content" in Rack 3.1, matching the HTTP specification's current name. Rails converts status symbols through Rack, so: - **`:unprocessable_content`** is the current symbol and maps to 422. - **`:unprocessable_entity`** is kept as an obsolete alias; it still returns 422, but Rack prints a deprecation warning saying it will be removed. - **`422`** as an integer always works. Rails' scaffold generator picks the symbol through `ActionDispatch::Constants::UNPROCESSABLE_CONTENT`, which is `:unprocessable_content` on Rack 3.1 or later and `:unprocessable_entity` on older Rack. Rails 8.1's own lockfile resolves Rack 3.2, and an app on Rack 3.1 or later gets `:unprocessable_content` in its generated controllers. ## The update path `update` follows the same rule with the edit template: `render :edit, status: :unprocessable_content`. The record is persisted, so the re-rendered form still posts with PATCH to the record's URL, and the attributes the user changed are shown from the in-memory object even though nothing was written. The success branch redirects with `status: :see_other` in the scaffold, so the browser follows it with a GET. ## render :new does not run new `render :new` picks the `new.html.erb` template and renders it with the instance variables the `create` action set. It does **not** call the `new` method. If `new` also loads data the template needs, such as `@teams = Team.order(:name)` for a select, `create` must load it too before rendering, or the form raises on `nil`. A private method or a `before_action` limited to both actions keeps them in step. ## Common mistakes - **Rendering without a status.** Works without Turbo, silently fails with it. - **Redirecting on failure** and trying to carry the errors in the flash instead. - **Re-fetching the record before rendering**, for example `@volunteer = Volunteer.find(params[:id])` in `update`'s failure branch, which replaces the object that holds the errors. - **Copying `:unprocessable_entity` from older code** into a Rails 8.1 app and ignoring the warning. ## Interview summary Render on failure because the errors and input exist only on the object in hand; answer 422 so Turbo Drive shows the result and clients and tests can tell failure from success. In Rails 8.1 that symbol is `:unprocessable_content`.

  • The new action sets @teams for a select. What breaks after a failed create, and how do you fix it?
    `render :new` does not run `new`, so `@teams` is nil and the select raises when it iterates. Load the list in `create`'s failure branch too, usually through a private method or a `before_action only: [:new, :create]`.
  • Why does the update action's failure path render :edit rather than :new?
    The record is persisted, so the edit template's form posts with PATCH to the record's URL. Rendering it from the same `@volunteer` keeps the user's changes and errors, again with status `:unprocessable_content`.
  • Is 422 the only acceptable status for a failed form submission?
    Turbo Drive renders any 4xx or 5xx, so 400 would also display. 422 is the convention because the request was well formed but the content was rejected, and it is what the Rails scaffold generator writes.

It is a teacher handing back your own exam with the mistakes marked in the margin. A redirect is handing you a fresh blank paper: your answers and the marks are both gone.

  • Redirecting back to the new page keeps the errors, because the flash carries them.
  • render :new runs the new action again before showing the template.
  • The status is cosmetic; render defaults to 422 when the model is invalid.
  • :unprocessable_entity is the current Rails 8.1 name for 422.
  • With Turbo Drive a 200 render after a failed POST displays the errors normally.

Assumes Rails 8.1 on Rack 3.1 or later, where 422 is :unprocessable_content and :unprocessable_entity is a deprecated alias that warns.