skip to content

Form Builders

Action View's form helpers build HTML forms from models or URLs, name fields so params nest, and re-render with errors after a failed save. Interviewers probe the whole form round trip.

part ofRuby on Railsread it →
on this pageshow

explore

questions

20

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.

open as a page

In a Rails form_with block, what HTML do f.label, f.text_field, f.email_field, f.textarea and f.hidden_field produce for a registration?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Each builder helper names its input registration[attribute], gives it the id registration_attribute, and fills it from the record. f.label points for= at that id and looks its text up through I18n, falling back to the attribute's human name.

open as a page

In a Rails 8.1 veterinary app, how can one _form partial built with form_with model: @pet serve both the new and the edit page?

level: juniorimportance: must knowfreq 78%

basics

~20 s

form_with model: reads the record: a new Pet posts to /pets, a saved one sends PATCH to /pets/7 because persisted? is true. Fields are named pet[...], prefilled from the record, and f.submit says Create Pet or Update Pet.

open as a page

Why does Rails' f.checkbox render a hidden input with value 0 before the checkbox, and how do you change or remove it?

level: middleimportance: must knowfreq 65%

basics

~20 s

Browsers omit unchecked checkboxes, so Rails writes a hidden input with the same name and value 0 first; when checked, the later 1 replaces it in params. Change it through checked and unchecked value arguments; remove it with include_hidden: false.

open as a page

Browsers submit forms only as GET or POST, so what HTML does Rails' form_with emit to reach a PATCH or DELETE route?

level: middleimportance: must knowfreq 60%

basics

~10 s

form_with keeps method="post" on the form tag and adds a hidden input named _method whose value is patch, put or delete. Rails' method-override middleware reads it, so routing sees the intended verb.

open as a page

In a Rails form, what input names does f.fields_for :ingredients produce for a has_many association, and when is a hidden id field added?

level: middleimportance: must knowfreq 55%

basics

~10 s

When Cocktail responds to ingredients_attributes=, f.fields_for :ingredients repeats its block per ingredient with names like cocktail[ingredients_attributes][0][name], then [1], and so on. Saved ingredients also get a hidden [id] input; new ones do not.

open as a page

In a Rails form view, how do you show a model's validation errors both as a summary above the form and beside each field?

level: juniorimportance: should knowfreq 55%

basics

~10 s

Above the form, loop over the record's errors when errors.any? and print each error.full_message, as the scaffold's _form partial does. Beside a field, print errors.full_messages_for(:email), which holds only that attribute's messages.

open as a page

In a Rails form, what does f.file_field change about the surrounding form_with, and what does the controller receive for an uploaded CV?

level: juniorimportance: should knowfreq 45%

basics

~10 s

f.file_field marks the builder as multipart, so form_with adds enctype="multipart/form-data" without being asked. The controller receives an ActionDispatch::Http::UploadedFile under params[:registration][:cv], and the field is never refilled on re-render.

open as a page

In Rails, what does the field_with_errors wrapper do to a form with invalid fields, and how do you change it with field_error_proc?

level: middleimportance: should knowfreq 40%

basics

~10 s

When a field's attribute has errors, Rails passes the field's HTML through field_error_proc, which by default wraps it in <div class="field_with_errors">. Set config.action_view.field_error_proc to a different proc to change or remove that wrapper app-wide.

open as a page

In a Rails form flow, when does a problem go in the model's errors rather than the flash, and why use flash.now before render?

level: middleimportance: should knowfreq 45%

basics

~20 s

Input problems belong in the model's errors, shown by the re-rendered form; the flash carries a short message across a redirect, like a success notice. For a banner on a re-render use flash.now, or it repeats on the next page.

open as a page

In a Rails form, how do f.select, options_for_select and f.collection_select differ, and how does each decide which option is selected?

level: middleimportance: should knowfreq 55%

basics

~20 s

f.select takes choices such as [text, value] pairs and preselects the record's current value; options_for_select only renders option tags; f.collection_select builds options from records with a value method and a text method, also preselecting from the record.

open as a page

In Rails 8.1, how do legacy form_for and form_tag differ from form_with, and what changes when you migrate an old form?

level: middleimportance: should knowfreq 40%

basics

~20 s

form_for bound a record and form_tag built a model-less form with *_tag helpers; form_with, added in Rails 5.1, covers both through model:, url: and scope:. Both old helpers still work in 8.1 but are discouraged.

open as a page

In Rails, when do you pass model:, url: or scope: to form_with, and how does each one change the action and the field names?

level: middleimportance: should knowfreq 48%

basics

~20 s

model: infers the action, the verb and the field prefix from a record; url: sets only the action, and without a model the fields are unprefixed; scope: sets only the prefix. Explicit options override what the model would infer.

open as a page

In a Rails nested form, how does a _destroy checkbox inside fields_for remove a saved child record, and what must be in place?

level: middleimportance: should knowfreq 45%

basics

~10 s

Inside fields_for, f.checkbox :_destroy posts cocktail[ingredients_attributes][0][_destroy] as 1 when ticked, beside the row's hidden id. The parent's accepts_nested_attributes_for needs allow_destroy: true, and the row is deleted only when the parent saves.

open as a page

A Rails volunteer form's summary lists a team error, yet the team select is never marked invalid; why do some errors never appear beside any field?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Per-field display looks up errors under the field's own method name. belongs_to :team adds "must exist" under :team while the select is team_id, so nothing matches. :base errors and fields missing from the form behave the same way.

open as a page

In a Rails registration form, which field helpers add hidden inputs of their own, and how can those values corrupt saved array data?

level: seniorimportance: should knowfreq 28%

basics

~20 s

checkbox, select with multiple: true, collection_checkboxes, collection_radio_buttons and multiple file_field add hidden inputs so an empty choice still submits; radio_button does not. In array params those values arrive as "0" or "" and can be saved unless stripped.

open as a page

How do you write a custom FormBuilder in Rails so every clinic form renders consistent field markup, and how do you make forms use it?

level: seniorimportance: should knowfreq 32%

basics

~10 s

Subclass ActionView::Helpers::FormBuilder, add or override field methods that call @template helpers and super, then select it per form with builder:, per controller with default_form_builder, or app-wide with config.action_view.default_form_builder.

open as a page

In a Rails nested form, how do you render a template for new ingredient rows so JavaScript can add any number of them without name collisions?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Render one blank child inside a <template> with f.fields_for :ingredients, Ingredient.new, child_index: "NEW_RECORD". JavaScript clones it and replaces NEW_RECORD with a fresh number such as Date.now(), so every added row gets unique names.

open as a page

In a Rails form_with block, how do you group inputs under their own key, such as cocktail[launch][announce], when no model or association backs them?

level: juniorimportance: nice to knowfreq 20%

basics

~20 s

Call form.fields :launch and build inputs on the builder it yields, which names them cocktail[launch][announce]. It renders no form tag and no hidden id, and fields start blank unless you pass model: with an object to read from.

open as a page

In a Rails nested form that renders each ingredient as a table row, why does the automatic hidden id end up outside the row, and when do you pass include_id: false?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

fields_for appends the hidden id after the block's output, so when the block renders a <tr> the input lands between rows. Render f.hidden_field :id inside a cell, or pass include_id: false when the child should post no id.

open as a page