skip to content

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%

answer

  1. form.fields :launch
  2. no <form> tag, no hidden id
  3. values blank unless model: given
  4. writer present: _attributes names
  5. params[:cocktail][:launch]

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.

solid answer

~40 s

`form.fields :launch do |launch| ... end` yields a `FormBuilder` scoped under the parent's key, so `launch.checkbox :announce` posts `cocktail[launch][announce]`. It renders only the inputs, no `<form>` tag, and adds no hidden id, because no record is bound. Values come from nowhere unless you pass one: `form.fields :launch, model: launch_options` reads values from any object with those readers, such as an `ActiveModel::Model` form object, or you set `value:` per field. The controller then reads `params[:cocktail][:launch]`, and must keep it out of `Cocktail.new`, which would raise `ActiveModel::UnknownAttributeError` for `launch`. One catch: if `Cocktail` does respond to `launch_attributes=`, `form.fields :launch` switches to nested-attributes names exactly as `fields_for` does. Outside a form, the template-level `fields :filter` scopes inputs as `filter[...]`.

code

ruby · 11 lines
ruby
def create
  @cocktail = Cocktail.new(params.expect(cocktail: [:name]))
  launch = params.expect(cocktail: [launch: [:announce, :starts_on]])[:launch]

  if @cocktail.save
    AnnounceCocktailJob.perform_later(@cocktail, launch[:starts_on]) if launch[:announce] == "1"
    redirect_to @cocktail
  else
    render :new, status: :unprocessable_content
  end
end

go deeper

for a junior

Recall that form.fields :launch scopes inputs as cocktail[launch][...] without adding a form tag, and that values need an object or value:.

for a middle

Explain how fields relates to fields_for, when it switches to _attributes names, and why the params must be kept out of the model's attribute hash.

for a senior

Choose between loose scoped fields and an ActiveModel form object when the extra inputs need validation, errors and a clear place in the controller.

for a principal

Set a team rule for non-model inputs, form objects versus scoped hashes, so controllers stay small and every input has an owner.

## The helper `fields` is the form-tag-less sibling of `form_with`. It yields a form builder that prefixes every input name with a scope, but it renders no `<form>` element, no authenticity token and no `_method` field. Inside a `form_with model: @cocktail` block, calling it on the builder nests the scope under the parent's key: ```erb <%= form_with model: @cocktail do |form| %> <%= form.text_field :name %> <%= form.fields :launch do |launch| %> <%= launch.checkbox :announce %> <%= launch.label :announce, "Announce on the menu board" %> <%= launch.date_field :starts_on %> <% end %> <% end %> ``` The inputs are named `cocktail[launch][announce]` and `cocktail[launch][starts_on]`, with ids such as `cocktail_launch_announce`. ## What you get and what you do not - **Names**: parent key, then the scope, then the field. - **No hidden id**: nothing persisted is bound, so there is nothing to identify. - **No values by default**: with no object the builder has nothing to read, so text fields render empty and checkboxes unticked. - **No nesting magic**: unless the parent responds to `launch_attributes=`; then the call switches to nested-attributes names, the same as `fields_for`. ## Giving the fields values Two common ways: 1. **Pass an object**: `form.fields :launch, model: @launch` reads `announce` and `starts_on` from any object that responds to them. An `ActiveModel::Model` class with `ActiveModel::Attributes` is the usual choice, because it can also validate and carry errors. 2. **Set values per field**: `launch.date_field :starts_on, value: Date.current`. A minimal form object for the launch options: ```ruby class LaunchOptions include ActiveModel::Model include ActiveModel::Attributes attribute :announce, :boolean, default: false attribute :starts_on, :date end ``` With `form.fields :launch, model: LaunchOptions.new(starts_on: Date.current)` the date field is prefilled. The explicit `:launch` scope wins over the object's own model name, so the inputs keep the `cocktail[launch][...]` names. ## Where the params go The controller sees a nested hash, `params[:cocktail][:launch]`. It belongs to no column on `Cocktail`, so: - passing it to `Cocktail.new` would call `launch=`, which does not exist, and Active Record raises `ActiveModel::UnknownAttributeError`; - the usual pattern is to permit it separately and hand it to whatever acts on it, such as a job that posts the announcement or a form object. Permitting the hash is the strong-parameters leaf's ground; the point here is only that it arrives beside the model's attributes, not inside them. ## Related helpers compared | Call | Names | Hidden id | Values from | |---|---|---|---| | `form.fields :launch` | `cocktail[launch][...]` | never | `model:` or `value:` | | `form.fields_for :ingredients` with the writer present | `cocktail[ingredients_attributes][0][...]` | persisted children | each child record | | `form.fields_for :launch` without a writer | `cocktail[launch][...]` | never | the object passed as the second argument | | template-level `fields :filter` | `filter[...]` | never | `model:`, `value:`, or an `@filter` instance variable | | `fields model: Ingredient.new` | `ingredient[...]` | never | the model | The template-level forms are handy inside a partial that is rendered into several different forms, or into a `form_with url:` search form. ## Interview summary Use `fields` to scope inputs that belong to no record: you get clean nested names, no `<form>` and no id. Bind it to a plain object with `model:` when the inputs need values or validation, and keep the resulting params out of the Active Record model they sit beside.

  • How do fields and fields_for differ when the parent has no matching _attributes= writer?
    They produce the same `cocktail[launch][...]` names. `fields` takes its object through the `model:` keyword, while `fields_for` takes it as the second positional argument; both switch to nested-attributes names only when the parent responds to `launch_attributes=`.
  • How would you validate the launch options and show their errors?
    Bind them to a form object that includes `ActiveModel::Model`, pass it as `model:`, and call `valid?` in the controller. The builder then reads its values, and the error wrapper and messages work as they do for a record.

  • form.fields renders its own nested <form> tag inside the parent form.
  • form.fields :launch always posts cocktail[launch_attributes][...] names.
  • The fields' inputs are prefilled from params on a re-render without any object.
  • Cocktail.new silently ignores the unknown launch key in its attributes.