skip to content

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%

answer

  1. three knobs, three jobs
  2. url: alone means bare field names
  3. scope: only renames the prefix
  4. url: replaces the action, not the verb
  5. an array model builds a nested URL

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.

solid answer

~40 s

`model:` is for forms that edit a record: it supplies the URL, PATCH for a persisted record, values from the record, and the `param_key` prefix, as in `pet[name]`. `url:` alone suits forms with no record, such as a search box or a login: the action is whatever you pass and the field names are bare, so `f.text_field :q` arrives as `params[:q]`. `scope:` groups those names, so `scope: :filter` gives `filter[q]`. The options combine: `model:` with `url:` keeps the PATCH inference but posts to your custom route; `model:` with `scope:` keeps the URL but renames the params. An array such as `model: [@owner, Pet.new]` targets the nested `/owners/3/pets` while the builder binds the last element.

code

erb · 14 lines
erb
<%# Filter list: no record, GET, grouped params -> params[:filter][:species] %>
<%= form_with url: pets_path, scope: :filter, method: :get do |f| %>
  <%= f.search_field :species %>
<% end %>

<%# Saved pet, custom route: still PATCH, still pet[...] %>
<%= form_with model: @pet, url: transfer_pet_path(@pet) do |f| %>
  <%= f.number_field :owner_id %>
<% end %>

<%# Nested create: posts to /owners/3/pets, fields pet[...] %>
<%= form_with model: [@owner, Pet.new] do |f| %>
  <%= f.text_field :name %>
<% end %>

go deeper

for a junior

Remember the defaults: model: for records, url: for forms without one, and that url:-only fields arrive unprefixed in params.

for a middle

Explain how the options combine: url: replaces only the action, scope: only the prefix, and the verb still comes from persisted? or method:.

for a senior

Show judgment on nested routes, form objects without routes and pages with two forms for one model, and know that a nil builder object breaks helpers that assume a record.

for a principal

Discuss when non-standard actions belong in their own resource instead of a model form with a custom url:, keeping routes and params predictable across a team.

## Three options, three separate jobs `form_with` builds three things: the form's **action** (where it submits), its **verb** (POST or a tunnelled PATCH), and the **names** of the fields inside it. Its three main options each control a different subset: | Option | Action | Verb | Field names | Field values | |---|---|---|---|---| | `model: record` | from the record's route | PATCH if `persisted?` | `param_key[...]` | read from the record | | `url: path` | exactly `path` | POST unless `method:` | unprefixed | none | | `scope: :key` | unchanged | unchanged | `key[...]` | unchanged | An explicit option always beats an inferred one, so the three combine predictably. ## `model:` for record-backed forms A form that creates or edits a record should pass the record. `form_with model: @pet` derives the action through Rails' polymorphic route lookup, adds PATCH when the record is persisted, binds the builder so `f.object` is the pet, fills field values from its attributes, and scopes field names with `model_name.param_key`. Controllers then read one nested hash, `params[:pet]`. An **array** passes a parent for nested routes: `form_with model: [@owner, Pet.new]` posts to `/owners/3/pets`, while the builder binds only the last element, so names are still `pet[...]`. Adding `format: :json` to a model form appends the format to the URL it derives. ## `url:` for forms with no record Search boxes, sign-in forms and filters often have no model to bind: - `form_with url: pets_path, method: :get` gives a GET form whose `f.search_field :species` arrives as `params[:species]`. - Without a model, the builder's `object` is `nil`, so fields render empty and nothing is inferred. - `url: false` omits the `action` attribute altogether, leaving the browser to submit to the current page. Passing `url:` together with `model:` changes only the action. A persisted pet with `url: transfer_pet_path(@pet)` still gets the hidden PATCH, still binds the record, and still names fields `pet[...]`. If the custom route expects POST, add `method: :post` as well. ## `scope:` for naming `scope:` sets the prefix and nothing else: 1. With `url:`, it groups loose fields: `form_with url: pets_path, scope: :filter, method: :get` produces `filter[species]`, read back as `params[:filter]`. 2. With `model:`, it renames the record's prefix: `form_with model: @pet, scope: :patient` keeps the URL and verb but submits `patient[name]`, which the controller must then read under `:patient`. Renaming a model's prefix is rare and easy to regret, because the controller's parameter handling and any tests must follow it. It earns its place when two forms for the same model share a page and their params must not collide. ## Form objects A plain Ruby object that includes `ActiveModel::API` (or `ActiveModel::Model`) can be passed to `model:` too. Its `persisted?` returns `false`, so the form always posts, and its `param_key` comes from the class name: a `PetTransfer` form object gives `pet_transfer[...]`. If no route matches the class, pass `url:` explicitly; the builder still binds the object, so field values and `f.object` work. ## What the controller receives The option choice decides the shape of `params`, which is what the controller code has to match: - `form_with model: @pet` gives `params[:pet][:name]`. - `form_with model: @pet, scope: :patient` gives `params[:patient][:name]`. - `form_with url: pets_path` gives `params[:species]` at the top level, next to `controller` and `action`. - `form_with url: pets_path, scope: :filter` gives `params[:filter][:species]`, one hash that is easy to pass to a query object. Grouping a search form under a scope also keeps its keys from colliding with route parameters such as `:id` or `:format`. ## Choosing in practice - Editing or creating a record: `model:` and nothing else. - A record, but a non-standard action: `model:` plus `url:` (plus `method:` when the verb differs). - No record: `url:`, with `scope:` when the fields should arrive as one nested hash. - Two forms for one model on a page: `model:` plus distinct `scope:` values. The red flag in an interview is believing that `url:` resets everything, or that bare `url:` forms still nest their params under some default key.

  • Why does the builder's object become nil in a url:-only form, and why does that matter?
    Without `model:` there is no record to bind, so `f.object` is `nil` and fields render without values. Helpers that read the record, such as a custom builder method calling `object.errors`, must guard against `nil` or they raise `NoMethodError` on search and login forms.
  • What does form_with model: [@owner, @pet] bind, and what does it post to?
    The URL comes from the whole array, so a saved pet posts a PATCH to `/owners/3/pets/7`. The builder binds only the last element, so `f.object` is the pet and field names are `pet[...]`, not `owner[...]`.

  • Passing url: to form_with turns a saved record's form back into a POST.
  • A url:-only form nests its fields under a default params key.
  • scope: changes the form's action as well as the field names.
  • form_with model: [@owner, @pet] names the fields owner[...].
  • A form object must be persisted to use model:, otherwise form_with raises.