instance method
fields
Ruby on Rails 7.1.6
Since v5.2.8.1Signature
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
-
scopeopt = nil -
modelkey = nil -
optionskeyrest -
blockblock
Source
# File actionview/lib/action_view/helpers/form_helper.rb, line 1077
def fields(scope = nil, model: nil, **options, &block)
options = { allow_method_names_outside_object: true, skip_default_ids: !form_with_generates_ids }.merge!(options)
if model
model = _object_for_form_builder(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 1077
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::FormHelper