skip to content

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%

answer

  1. subclass, don't patch
  2. ActionView::Helpers::FormBuilder
  3. @template for view helpers
  4. objectify_options keeps the record
  5. builder:, default_form_builder, config.action_view

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.

solid answer

~40 s

A custom builder is a subclass of `ActionView::Helpers::FormBuilder`. Inside it, `@template` is the view context for helpers like `tag` and `safe_join`, `object` (also `f.object`) is the bound record, and `object_name` is the param prefix. You either override a standard method, say `text_field`, adjust `options` and call `super`, or add composite methods such as `labelled_field` that combine `label`, a field and a hint. When you delegate to a raw view helper yourself, pass `objectify_options(options)` so the record travels with it. To apply it: `builder: ClinicFormBuilder` on one form, `default_form_builder ClinicFormBuilder` in a controller for its views and subclasses, or `config.action_view.default_form_builder = "ClinicFormBuilder"` app-wide. The order of precedence is the same: per form, then controller, then app.

code

ruby · 17 lines
ruby
# app/form_builders/clinic_form_builder.rb
class ClinicFormBuilder < ActionView::Helpers::FormBuilder
  def text_field(method, options = {})
    options[:class] = ["input", options[:class]].compact.join(" ")
    super
  end

  def labelled_field(method, hint: nil, **options)
    @template.tag.div(class: "field") do
      @template.safe_join([
        label(method),
        text_field(method, options),
        (@template.tag.p(hint, class: "hint") if hint)
      ].compact)
    end
  end
end

go deeper

for a junior

Know that form_with yields a FormBuilder and that a team can swap in its own subclass to change how f.text_field renders.

for a middle

Explain @template, object and objectify_options, and the three ways to select a builder with their precedence.

for a senior

Show production care: nil objects in url:-only forms, escaping through tag and safe_join, reloadable registration by string, and keeping error display consistent with Rails' conventions.

for a principal

Decide between a builder, partials and a component library for the design system, weighing invisibility of overrides against explicitness and team onboarding.

## Why teams write a builder Every `form_with` block yields a **form builder**, by default an `ActionView::Helpers::FormBuilder`. Its methods (`text_field`, `label`, `select` and the rest) know the record and the param prefix, so they write names, ids and values for you. A clinic app with dozens of forms usually wants the same wrapper `div`, CSS classes, hint text and `required` marker on every field. Copying that markup into each template drifts; a partial per field type is clumsy to call. A **custom builder** keeps the familiar `f.text_field :name` call and changes what it renders, everywhere at once. ## The pieces inside a builder - **`@template`**: the view context. A builder is not a view, so helpers such as `tag`, `safe_join` and `content_tag` are called on `@template`. - **`object`** (also reachable as `f.object` from the view): the bound record, or `nil` for a `url:`-only form. - **`object_name`**: the param prefix, such as `"pet"`. - **`options`**: the options the form was built with. - **`objectify_options(options)`**: a private helper that merges the builder's defaults and adds `object:`. Call it when you invoke a raw view helper, such as `@template.radio_button(@object_name, method, value, objectify_options(options))`, or the generated field loses its link to the record. - **`field_helpers`**: a class attribute listing the standard wrapped methods; the stock builder defines most of them in a loop that delegates each call to `@template`. ## Two ways to extend 1. **Override a standard method.** Change the options and call `super`, so every `f.text_field` gets your classes without template edits. 2. **Add a composite method.** Something like `labelled_field(:microchip_number, hint: "15 digits")` that renders the wrapper, the label, the field and the hint in one call. Overriding is invisible to template authors, which is both its strength and its risk: someone reading `f.text_field` sees no hint that markup changes. Composite methods are explicit but must be learned. ## Selecting the builder | Scope | How | Typical use | |---|---|---| | One form | `form_with model: @pet, builder: ClinicFormBuilder` | trying a builder out, one-off layouts | | A controller tree | `default_form_builder ClinicFormBuilder` in the controller class | an admin area with its own styling | | Whole app | `config.action_view.default_form_builder = "ClinicFormBuilder"` | one design system | At render time Action View takes the `builder:` option first, then the controller's `default_form_builder`, then the app-wide setting. The controller macro comes from `ActionController::FormBuilder` and is inherited, so declaring it on `Admin::BaseController` covers every admin controller. The app-wide setting accepts a string, which is constantized when a form is built, so the class can live in an autoloaded directory such as `app/form_builders/` and still reload in development. ## Where the builder reaches The builder chosen for a form is the one yielded to its block, and it travels further than the top-level fields: - Child forms opened with `f.fields_for` reuse the parent's `builder:` option, so nested rows render with the same markup. - Every helper on the builder, standard or custom, sees the same `object_name`, so overriding `label` once changes labels in every form that uses the builder. - `f.submit` and `f.button` are builder methods too, so button styling can live in the builder as well. This reach is the point of the exercise: one class decides how a field looks across the app, and a template only says which field it wants. ## Production pitfalls - **`nil` objects.** In `form_with url: search_path`, `object` is `nil`. Builder code that reads `object.errors` or `object.class` must guard with `object&.` or check `object` first. - **Escaping.** Build markup with `@template.tag` and `@template.safe_join`; concatenating strings and calling `html_safe` invites XSS when a hint or label contains user data. - **Hidden coupling.** If the builder adds classes your CSS depends on, a form built with a different `builder:` silently loses its styling. Document the builder as part of the design system. - **Error display.** Builders are a common place to render per-field errors, but how Rails wraps invalid fields and reports messages belongs to error-display conventions; keep the builder consistent with them instead of inventing a second scheme. ## Alternatives Partials and view helpers can render field groups, and component libraries such as ViewComponent or Phlex give each field group a class of its own. A builder remains the lightest option when the goal is "the same `f.` calls, different markup", because it plugs into `form_with` without changing how templates are written.

  • Why does the stock FormBuilder documentation insist on objectify_options in custom methods?
    Raw view helpers such as `@template.radio_button(@object_name, method, value, options)` find the record through `options[:object]`. `objectify_options` merges the builder's default options and sets `object:` to the bound record. Skipping it makes the field look up an instance variable instead, which often misses, so values and checked state stop reflecting the record.
  • Why pass default_form_builder in config as a string rather than the class?
    A string is constantized only when a form is built, after initialization, so the builder can live in an autoloaded directory like `app/form_builders/` and be reloaded on each request in development. Naming the class itself in `config/application.rb` would require loading it during boot.

  • Monkey-patch ActionView::Helpers::FormBuilder directly instead of subclassing it.
  • Inside a builder you can call tag and safe_join directly, because FormBuilder includes the view helpers.
  • Register the builder in a controller with the helper macro.
  • Builder methods can always call object.errors, since form_with always binds a record.
  • config.action_view.default_form_builder only affects forms that pass builder: explicitly.