instance method fields

Ruby on Rails 6.1.7.10

Since v5.2.8.1

Available in: v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

fields(scope = nil, model: nil, **options, &block)

Scopes input fields with either an explicit scope or model. Like form_with does with :scope or :model, except it doesn’t output the form tags.

# Using a scope prefixes the input field names:
<%= fields :comment do |fields| %>
  <%= fields.text_field :body %>
<% end %>
# => <input type="text" name="comment[body]">

# Using a model infers the scope and assigns field values:
<%= fields model: Comment.new(body: "full bodied") do |fields| %>
  <%= fields.text_field :body %>
<% end %>
# => <input type="text" name="comment[body]" value="full bodied">

# Using +fields+ with +form_with+:
<%= form_with model: @post do |form| %>
  <%= form.text_field :title %>

  <%= form.fields :comment do |fields| %>
    <%= fields.text_field :body %>
  <% end %>
<% end %>

Much like form_with a FormBuilder instance associated with the scope or model is yielded, so any generated field names are prefixed with either the passed scope or the scope inferred from the :model.

Mixing with other form helpers

While form_with uses a FormBuilder object it’s possible to mix and match the stand-alone FormHelper methods and methods from FormTagHelper:

<%= fields model: @comment do |fields| %>
  <%= fields.text_field :body %>

  <%= text_area :commenter, :biography %>
  <%= check_box_tag "comment[all_caps]", "1", @comment.commenter.hulk_mode? %>
<% end %>

Same goes for the methods in FormOptionsHelper and DateHelper designed to work with an object as a base, like FormOptionsHelper#collection_select and DateHelper#datetime_select.

Parameters

scope opt = nil
model key = nil
options keyrest
block block
Source
# File actionview/lib/action_view/helpers/form_helper.rb, line 1052
      def fields(scope = nil, model: nil, **options, &block)
        options[:allow_method_names_outside_object] = true
        options[:skip_default_ids] = !form_with_generates_ids

        if model
          scope ||= model_name_from_record_or_class(model).param_key
        end

        builder = instantiate_builder(scope, model, options)
        capture(builder, &block)
      end

Defined in actionview/lib/action_view/helpers/form_helper.rb line 1052 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::FormHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close