skip to content

Model vs URL Targets

form_with model: derives the URL, HTTP method and param scope from the record, sending PATCH through a hidden _method field once it is persisted. Interviewers probe that inference and custom builders.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

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%

answer

  1. the record decides, not the template
  2. persisted? flips create to update
  3. /pets vs /pets/7
  4. param_key names the fields pet[...]
  5. f.submit: Create Pet or Update Pet

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.

solid answer

~40 s

The partial never says which page it is on; the record does. `form_with model: pet` builds the action from the record's route, so `Pet.new` targets `/pets` and a saved pet targets `/pets/7`. It then asks `pet.persisted?`: false keeps the request a POST to `create`, true turns it into a PATCH to `update`. The builder scopes every field under the model's `param_key`, so `f.text_field :name` becomes `name="pet[name]"`, prefilled from `pet.name`, and the controller reads `params[:pet]`. A bare `f.submit` follows the same switch and labels itself "Create Pet" or "Update Pet". So `new` and `edit` each assign `@pet` (`Pet.new` or `Pet.find`) and render `_form` with `pet: @pet`, and the one template serves both pages.

code

erb · 17 lines
erb
<%# app/views/pets/_form.html.erb %>
<%= form_with model: pet do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :species %>
  <%= f.text_field :species %>

  <% if f.object.persisted? %>
    <p>Registered on <%= l(f.object.created_at.to_date) %></p>
  <% end %>

  <%= f.submit %>
<% end %>

<%# app/views/pets/new.html.erb and edit.html.erb %>
<%= render "form", pet: @pet %>

go deeper

for a junior

Recall that the record decides: a new Pet makes a create form, a saved Pet makes an update form, and fields arrive in params[:pet]. Be ready to sketch the partial and the two render calls.

for a middle

Explain the three inferences separately: the route lookup gives the URL, persisted? gives the verb, and param_key gives the field prefix. Mention that f.submit's label follows the same switch through I18n keys.

for a senior

Show where the inference stops: a form object without a route needs url:, ActiveModel::API objects always report persisted? false, and explicit url:, scope: or method: options override what the record says.

for a principal

Frame the pattern as a convention trade: one partial per resource keeps forms consistent, but it couples markup to routes; judge when a form object or a separate flow is worth breaking it.

## The problem one partial solves A **pet profile** in a veterinary app needs two pages: one to register a new animal and one to correct an existing profile. Their fields are identical (name, species, date of birth, microchip number); only the destination differs. A new profile must reach the `create` action, an existing one the `update` action. Rails lets a single partial, `app/views/pets/_form.html.erb`, serve both, because **`form_with model:`** works out the destination from the record you hand it instead of from anything written in the template. ## What `form_with model:` reads from the record When you call `form_with model: pet`, Action View asks the record three questions: 1. **Which URL?** It resolves the record's route through Rails' polymorphic route lookup. A `Pet` that has not been saved resolves to the collection path `/pets`; a saved `Pet` with id 7 resolves to the member path `/pets/7`. 2. **Which HTTP verb?** It calls **`persisted?`**. On an Active Record model, `persisted?` is true when the record is neither a new record nor destroyed. True means the form is an update and gets PATCH; false leaves it a plain POST. 3. **Which parameter key?** It takes `model_name.param_key`, which for `Pet` is `"pet"`, and uses it as the **scope** for every field the builder generates. The verb decision rests on `persisted?`, not on whether an `id` is set: `Pet.new(id: 5)` is still a new record, so it posts to create. ## What the builder does with that The block receives a **`FormBuilder`** (`f`) bound to the record and its scope: - `f.text_field :name` renders `name="pet[name]"` and fills `value` from `pet.name`, so the edit page shows the current data and the new page shows blanks. - `f.label :name` points `for=` at the field's id, `pet_name`, because a new app's `load_defaults` make `form_with` generate ids. - `f.submit` with no argument looks up a label through I18n: `helpers.submit.create` ("Create %{model}") for a new record, `helpers.submit.update` ("Update %{model}") for a saved one, giving **"Create Pet"** or **"Update Pet"**. - `f.object` returns the record itself, so the partial can still branch when it must, for example to show a "Registered on" line only when `f.object.persisted?`. The controller reads `params[:pet]` in both `create` and `update`, because both forms scope their fields under the same key. ## Wiring the two pages | Page | Controller sets | Form targets | Verb seen by routes | Submit label | |---|---|---|---|---| | `new` | `@pet = Pet.new` | `/pets` | POST, so `create` | Create Pet | | `edit` | `@pet = Pet.find(params[:id])` | `/pets/7` | PATCH, so `update` | Update Pet | Both `new.html.erb` and `edit.html.erb` hold little more than a heading and `render "form", pet: @pet`. Passing the record as a local, instead of reading `@pet` inside the partial, keeps the partial reusable from other templates. ## Where the inference stops - The record must have a route. `form_with model: pet` raises if no `pets` route exists, because it cannot build the URL; a form object with no matching resource needs an explicit `url:`. - A model that is not Active Record decides through its own `persisted?`. Including `ActiveModel::API` gives you a `persisted?` that always returns false, so such an object always posts. - Anything passed explicitly wins: `url:` replaces the action, `scope:` replaces the field prefix, and `method:` replaces the verb. ## Mistakes that break the pattern - **Building the record in the view.** `form_with model: Pet.new` inside the partial makes the edit page render a create form; the controller must supply the right record. - **Assigning a fresh record on a failed update.** If `update` re-renders `edit` with `Pet.new(pet_params)`, the form flips to create. Re-render with the loaded record whose attributes were assigned. - **Hard-coding `url:` in the partial.** A fixed `url: pets_path` sends edits to `create`; leave the URL to the record unless a route really differs. ## What interviewers listen for A junior answer names the pieces: one partial, `form_with model:`, the record decides between create and update. A stronger answer names the mechanism: `persisted?` picks the verb, the route lookup picks the URL, `param_key` names the fields, and `f.submit` follows the same switch. Saying "Rails checks whether the id is present" or "you need an `if` in the template" signals that the candidate has used the pattern without knowing why it works.

  • Why does Pet.new(id: 5) still produce a create form?
    `form_with` checks `persisted?`, not the id. On an Active Record model `persisted?` is true only when the record was loaded or saved and not destroyed. Assigning an id to a new object leaves it a new record, so the form posts to `/pets`, the collection path, and the submit button says "Create Pet".
  • How would you change the submit label for pets only, without passing a string to f.submit?
    Add an I18n key under `helpers.submit.pet`, for example `create: "Register %{model}"` and `update: "Save changes to %{model}"`. A bare `f.submit` looks up the model-specific key first, then the generic `helpers.submit.create` or `helpers.submit.update`, so every pet form picks up the new wording.
  • What breaks if the partial reads @pet instead of a pet local?
    It still renders, but it is now tied to whatever instance variable the calling controller set. Rendering the partial from another template, such as an owner's page that builds a pet inline, means setting `@pet` there too. Passing `pet:` as a local makes the dependency explicit and the partial reusable.

  • You need separate new and edit partials because form_with cannot switch between create and update.
  • form_with model: decides on PATCH when the record's id attribute is set.
  • Field names come from the table name, so the params arrive under pets[name].
  • With a model, form_with posts to the current page's URL unless you pass url:.
  • A bare f.submit always says Save, so the label must be passed by hand.
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 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

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