Class: ActionView::Helpers::FormBuilder
- Inherits:
-
Object
- Object
- ActionView::Helpers::FormBuilder
- Includes:
- ModelNaming
- Defined in:
- lib/action_view/helpers/form_helper.rb,
lib/action_view/helpers/date_helper.rb,
lib/action_view/helpers/form_options_helper.rb
Overview
Action View Form Builder
A FormBuilder
object is associated with a particular model object and allows you to generate fields associated with the model object. The FormBuilder
object is yielded when using form_with
or fields_for
. For example:
<%= form_with model: @person do |person_form| %>
Name: <%= person_form.text_field :name %>
Admin: <%= person_form.check_box :admin %>
<% end %>
In the above block, a FormBuilder
object is yielded as the person_form
variable. This allows you to generate the text_field
and check_box
fields by specifying their eponymous methods, which modify the underlying template and associates the @person
model object with the form.
The FormBuilder
object can be thought of as serving as a proxy for the methods in the FormHelper
module. This class, however, allows you to call methods with the model object you are building the form for.
You can create your own custom FormBuilder templates by subclassing this class. For example:
class MyFormBuilder < ActionView::Helpers::FormBuilder
def (method, tag_value, = {})
@template.content_tag(:div,
@template.(
@object_name, method, tag_value, ()
)
)
end
end
The above code creates a new method div_radio_button
which wraps a div around the new radio button. Note that when options are passed in, you must call objectify_options
in order for the model object to get correctly passed to the method. If objectify_options
is not called, then the newly created helper will not be linked back to the model.
The div_radio_button
code from above can now be used as follows:
<%= form_with model: @person, :builder => MyFormBuilder do |f| %>
I am a child: <%= f.div_radio_button(:admin, "child") %>
I am an adult: <%= f.div_radio_button(:admin, "adult") %>
<% end -%>
The standard set of helper methods for form building are located in the field_helpers
class attribute.
Instance Attribute Summary collapse
-
#index ⇒ Object
readonly
Returns the value of attribute index.
-
#multipart ⇒ Object
(also: #multipart?)
Returns the value of attribute multipart.
-
#object ⇒ Object
Returns the value of attribute object.
-
#object_name ⇒ Object
Returns the value of attribute object_name.
-
#options ⇒ Object
Returns the value of attribute options.
Class Method Summary collapse
Instance Method Summary collapse
-
#button(value = nil, options = {}, &block) ⇒ Object
Add the submit button for the given form.
-
#check_box(method, options = {}, checked_value = "1", unchecked_value = "0") ⇒ Object
Returns a checkbox tag tailored for accessing a specified attribute (identified by
method
) on an object assigned to the template (identified byobject
). -
#collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:.
-
#collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:.
-
#collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:.
-
#date_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::DateHelper#date_select for form builders:.
-
#datetime_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:.
-
#emitted_hidden_id? ⇒ Boolean
:nodoc:.
-
#field_id(method, *suffixes, namespace: , index: ) ⇒ Object
Generate an HTML
id
attribute value for the given field. -
#field_name(method, *methods, multiple: false, index: ) ⇒ Object
Generate an HTML
name
attribute value for the given name and field combination. -
#fields(scope = nil, model: nil, **options, &block) ⇒ Object
See the docs for the ActionView::Helpers::FormHelper#fields helper method.
-
#fields_for(record_name, record_object = nil, fields_options = nil, &block) ⇒ Object
Creates a scope around a specific model object like form_with, but doesn’t create the form tags themselves.
-
#file_field(method, options = {}) ⇒ Object
Returns a file upload input tag tailored for accessing a specified attribute (identified by
method
) on an object assigned to the template (identified byobject
). -
#grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:.
-
#hidden_field(method, options = {}) ⇒ Object
Returns a hidden input tag tailored for accessing a specified attribute (identified by
method
) on an object assigned to the template (identified byobject
). -
#id ⇒ Object
Generate an HTML
id
attribute value. -
#initialize(object_name, object, template, options) ⇒ FormBuilder
constructor
A new instance of FormBuilder.
-
#label(method, text = nil, options = {}, &block) ⇒ Object
Returns a label tag tailored for labelling an input field for a specified attribute (identified by
method
) on an object assigned to the template (identified byobject
). -
#radio_button(method, tag_value, options = {}) ⇒ Object
Returns a radio button tag for accessing a specified attribute (identified by
method
) on an object assigned to the template (identified byobject
). -
#select(method, choices = nil, options = {}, html_options = {}, &block) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:.
-
#self ⇒ Object
:method: range_field.
-
#submit(value = nil, options = {}) ⇒ Object
Add the submit button for the given form.
-
#time_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::DateHelper#time_select for form builders:.
-
#time_zone_select(method, priority_zones = nil, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:.
- #to_model ⇒ Object
- #to_partial_path ⇒ Object
-
#weekday_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#weekday_select for form builders:.
Methods included from ModelNaming
#convert_to_model, #model_name_from_record_or_class
Constructor Details
#initialize(object_name, object, template, options) ⇒ FormBuilder
Returns a new instance of FormBuilder.
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 |
# File 'lib/action_view/helpers/form_helper.rb', line 1717 def initialize(object_name, object, template, ) @nested_child_index = {} @object_name, @object, @template, @options = object_name, object, template, @default_options = @options ? @options.slice(:index, :namespace, :skip_default_ids, :allow_method_names_outside_object) : {} @default_html_options = @default_options.except(:skip_default_ids, :allow_method_names_outside_object) (@options) if @object_name&.end_with?("[]") if (object ||= @template.instance_variable_get("@#{@object_name[0..-3]}")) && object.respond_to?(:to_param) @auto_index = object.to_param else raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" end end @multipart = nil @index = [:index] || [:child_index] end |
Instance Attribute Details
#index ⇒ Object (readonly)
Returns the value of attribute index.
1694 1695 1696 |
# File 'lib/action_view/helpers/form_helper.rb', line 1694 def index @index end |
#multipart ⇒ Object Also known as: multipart?
Returns the value of attribute multipart.
1694 1695 1696 |
# File 'lib/action_view/helpers/form_helper.rb', line 1694 def multipart @multipart end |
#object ⇒ Object
Returns the value of attribute object.
1692 1693 1694 |
# File 'lib/action_view/helpers/form_helper.rb', line 1692 def object @object end |
#object_name ⇒ Object
Returns the value of attribute object_name.
1692 1693 1694 |
# File 'lib/action_view/helpers/form_helper.rb', line 1692 def object_name @object_name end |
#options ⇒ Object
Returns the value of attribute options.
1692 1693 1694 |
# File 'lib/action_view/helpers/form_helper.rb', line 1692 def @options end |
Class Method Details
._to_partial_path ⇒ Object
1705 1706 1707 |
# File 'lib/action_view/helpers/form_helper.rb', line 1705 def self._to_partial_path @_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, "") end |
Instance Method Details
#button(value = nil, options = {}, &block) ⇒ Object
Add the submit button for the given form. When no value is given, it checks if the object is a new resource or not to create the proper label:
<%= form_with model: @article do |f| %>
<%= f.button %>
<% end %>
In the example above, if @article
is a new record, it will use “Create Article” as button label; otherwise, it uses “Update Article”.
Those labels can be customized using I18n under the helpers.submit
key (the same as submit helper) and using %{model}
for translation interpolation:
en:
helpers:
submit:
create: "Create a %{model}"
update: "Confirm changes to %{model}"
It also searches for a key specific to the given object:
en:
helpers:
submit:
article:
create: "Add %{model}"
Examples
("Create article")
# => <button name='button' type='submit'>Create article</button>
(:draft, value: true)
# => <button id="article_draft" name="article[draft]" value="true" type="submit">Create article</button>
do
content_tag(:strong, 'Ask me!')
end
# => <button name='button' type='submit'>
# <strong>Ask me!</strong>
# </button>
do |text|
content_tag(:strong, text)
end
# => <button name='button' type='submit'>
# <strong>Create article</strong>
# </button>
(:draft, value: true) do
content_tag(:strong, "Save as draft")
end
# => <button id="article_draft" name="article[draft]" value="true" type="submit">
# <strong>Save as draft</strong>
# </button>
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 |
# File 'lib/action_view/helpers/form_helper.rb', line 2649 def (value = nil, = {}, &block) case value when Hash value, = nil, value when Symbol value, = nil, { name: field_name(value), id: field_id(value) }.merge!(.to_h) end value ||= submit_default_value if block_given? value = @template.capture { yield(value) } end formmethod = [:formmethod] if formmethod.present? && !/post|get/i.match?(formmethod) && !.key?(:name) && !.key?(:value) .merge! formmethod: :post, name: "_method", value: formmethod end @template.(value, ) end |
#check_box(method, options = {}, checked_value = "1", unchecked_value = "0") ⇒ Object
Returns a checkbox tag tailored for accessing a specified attribute (identified by method
) on an object assigned to the template (identified by object
). This object must be an instance object (@object) and not a local object. It’s intended that method
returns an integer and if that integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a hash with options
. The checked_value
defaults to 1 while the default unchecked_value
is set to 0 which is convenient for boolean values.
Options
-
Any standard HTML attributes for the tag can be passed in, for example
:class
. -
:checked
-true
orfalse
forces the state of the checkbox to be checked or not. -
:include_hidden
- If set to false, the auxiliary hidden field described below will not be generated.
Gotcha
The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice
model has a paid
flag, and in the form that edits a paid invoice the user unchecks its check box, no paid
parameter is sent. So, any mass-assignment idiom like
@invoice.update(params[:invoice])
wouldn’t update the flag.
To prevent this the helper generates an auxiliary hidden field before every check box. The hidden field has the same name and its attributes mimic an unchecked check box.
This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.
Unfortunately that workaround does not work when the check box goes within an array-like parameter, as in
<%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %>
<%= form.check_box :paid %>
...
<% end %>
because parameter name repetition is precisely what Rails seeks to distinguish the elements of the array. For each item with a checked check box you get an extra ghost item with only that attribute, assigned to “0”.
In that case it is preferable to either use check_box_tag
or to use hashes instead of arrays.
Examples
# Let's say that @article.validated? is 1:
check_box("validated")
# => <input name="article[validated]" type="hidden" value="0" />
# <input checked="checked" type="checkbox" id="article_validated" name="article[validated]" value="1" />
# Let's say that @puppy.gooddog is "no":
check_box("gooddog", {}, "yes", "no")
# => <input name="puppy[gooddog]" type="hidden" value="no" />
# <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
# Let's say that @eula.accepted is "no":
check_box("accepted", { class: 'eula_check' }, "yes", "no")
# => <input name="eula[accepted]" type="hidden" value="no" />
# <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
2474 2475 2476 |
# File 'lib/action_view/helpers/form_helper.rb', line 2474 def check_box(method, = {}, checked_value = "1", unchecked_value = "0") @template.check_box(@object_name, method, (), checked_value, unchecked_value) end |
#collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:
<%= form_for @post do |f| %>
<%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
908 909 910 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 908 def collection_check_boxes(method, collection, value_method, text_method, = {}, = {}, &block) @template.collection_check_boxes(@object_name, method, collection, value_method, text_method, (), @default_html_options.merge(), &block) end |
#collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
<%= form_for @post do |f| %>
<%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
920 921 922 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 920 def (method, collection, value_method, text_method, = {}, = {}, &block) @template.(@object_name, method, collection, value_method, text_method, (), @default_html_options.merge(), &block) end |
#collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:
<%= form_for @post do |f| %>
<%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
860 861 862 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 860 def collection_select(method, collection, value_method, text_method, = {}, = {}) @template.collection_select(@object_name, method, collection, value_method, text_method, (), @default_html_options.merge()) end |
#date_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::DateHelper#date_select for form builders:
<%= form_for @person do |f| %>
<%= f.date_select :birth_date %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
1237 1238 1239 |
# File 'lib/action_view/helpers/date_helper.rb', line 1237 def date_select(method, = {}, = {}) @template.date_select(@object_name, method, (), ) end |
#datetime_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:
<%= form_for @person do |f| %>
<%= f.datetime_select :last_request_at %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
1261 1262 1263 |
# File 'lib/action_view/helpers/date_helper.rb', line 1261 def datetime_select(method, = {}, = {}) @template.datetime_select(@object_name, method, (), ) end |
#emitted_hidden_id? ⇒ Boolean
:nodoc:
2670 2671 2672 |
# File 'lib/action_view/helpers/form_helper.rb', line 2670 def emitted_hidden_id? # :nodoc: @emitted_hidden_id ||= nil end |
#field_id(method, *suffixes, namespace: , index: ) ⇒ Object
Generate an HTML id
attribute value for the given field
Return the value generated by the FormBuilder
for the given attribute name.
<%= form_with model: @article do |f| %>
<%= f.label :title %>
<%= f.text_field :title, aria: { describedby: f.field_id(:title, :error) } %>
<%= tag.span("is blank", id: f.field_id(:title, :error) %>
<% end %>
In the example above, the <input type="text">
element built by the call to FormBuilder#text_field
declares an aria-describedby
attribute referencing the <span>
element, sharing a common id
root (article_title
, in this case).
1774 1775 1776 |
# File 'lib/action_view/helpers/form_helper.rb', line 1774 def field_id(method, *suffixes, namespace: @options[:namespace], index: @options[:index]) @template.field_id(@object_name, method, *suffixes, namespace: namespace, index: index) end |
#field_name(method, *methods, multiple: false, index: ) ⇒ Object
Generate an HTML name
attribute value for the given name and field combination
Return the value generated by the FormBuilder
for the given attribute name.
<%= form_with model: @article do |f| %>
<%= f.text_field :title, name: f.field_name(:title, :subtitle) %>
<%# => <input type="text" name="article[title][subtitle]"> %>
<% end %>
<%= form_with model: @article do |f| %>
<%= f.text_field :tag, name: f.field_name(:tag, multiple: true) %>
<%# => <input type="text" name="article[tag][]"> %>
<% end %>
1794 1795 1796 1797 1798 |
# File 'lib/action_view/helpers/form_helper.rb', line 1794 def field_name(method, *methods, multiple: false, index: @options[:index]) object_name = @options.fetch(:as) { @object_name } @template.field_name(object_name, method, *methods, index: index, multiple: multiple) end |
#fields(scope = nil, model: nil, **options, &block) ⇒ Object
See the docs for the ActionView::Helpers::FormHelper#fields helper method.
2328 2329 2330 2331 2332 2333 2334 2335 |
# File 'lib/action_view/helpers/form_helper.rb', line 2328 def fields(scope = nil, model: nil, **, &block) [:allow_method_names_outside_object] = true [:skip_default_ids] = !FormHelper.form_with_generates_ids () fields_for(scope || model, model, , &block) end |
#fields_for(record_name, record_object = nil, fields_options = nil, &block) ⇒ Object
Creates a scope around a specific model object like form_with, but doesn’t create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form.
Although the usage and purpose of fields_for
is similar to form_with
‘s, its method signature is slightly different. Like form_with
, it yields a FormBuilder object associated with a particular model object to a block, and within the block allows methods to be called on the builder to generate fields associated with the model object. Fields may reflect a model object in two ways - how they are named (hence how submitted values appear within the params
hash in the controller) and what default values are shown when the form fields are first displayed. In order for both of these features to be specified independently, both an object name (represented by either a symbol or string) and the object itself can be passed to the method separately -
<%= form_with model: @person do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for :permission, @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<%= person_form.submit %>
<% end %>
In this case, the checkbox field will be represented by an HTML input
tag with the name
attribute permission[admin]
, and the submitted value will appear in the controller as params[:permission][:admin]
. If @person.permission
is an existing record with an attribute admin
, the initial state of the checkbox when first displayed will reflect the value of @person.permission.admin
.
Often this can be simplified by passing just the name of the model object to fields_for
-
<%= fields_for :permission do |permission_fields| %>
Admin?: <%= permission_fields.check_box :admin %>
<% end %>
…in which case, if :permission
also happens to be the name of an instance variable @permission
, the initial state of the input field will reflect the value of that variable’s attribute @permission.admin
.
Alternatively, you can pass just the model object itself (if the first argument isn’t a string or symbol fields_for
will realize that the name has been omitted) -
<%= fields_for @person.permission do |permission_fields| %>
Admin?: <%= permission_fields.check_box :admin %>
<% end %>
and fields_for
will derive the required name of the field from the class of the model object, e.g. if @person.permission
, is of class Permission
, the field will still be named permission[admin]
.
Note: This also works for the methods in FormOptionsHelper and DateHelper that are designed to work with an object as base, like FormOptionsHelper#collection_select and DateHelper#datetime_select.
fields_for
tries to be smart about parameters, but it can be confused if both name and value parameters are provided and the provided value has the shape of an option Hash. To remove the ambiguity, explicitly pass an option Hash, even if empty.
<%= form_with model: @person do |person_form| %>
...
<%= fields_for :permission, @person.permission, {} do |permission_fields| %>
Admin?: <%= check_box_tag permission_fields.field_name(:admin), @person.permission[:admin] %>
<% end %>
...
<% end %>
Nested Attributes Examples
When the object belonging to the current scope has a nested attribute writer for a certain attribute, fields_for will yield a new scope for that attribute. This allows you to create forms that set or change the attributes of a parent object and its associations in one go.
Nested attribute writers are normal setter methods named after an association. The most common way of defining these writers is either with accepts_nested_attributes_for
in a model definition or by defining a method with the proper name. For example: the attribute writer for the association :address
is called address_attributes=
.
Whether a one-to-one or one-to-many style form builder will be yielded depends on whether the normal reader method returns a single object or an array of objects.
One-to-one
Consider a Person class which returns a single Address from the address
reader method and responds to the address_attributes=
writer method:
class Person
def address
@address
end
def address_attributes=(attributes)
# Process the attributes hash
end
end
This model can now be used with a nested fields_for, like so:
<%= form_with model: @person do |person_form| %>
...
<%= person_form.fields_for :address do |address_fields| %>
Street : <%= address_fields.text_field :street %>
Zip code: <%= address_fields.text_field :zip_code %>
<% end %>
...
<% end %>
When address is already an association on a Person you can use accepts_nested_attributes_for
to define the writer method for you:
class Person < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
If you want to destroy the associated model through the form, you have to enable it first using the :allow_destroy
option for accepts_nested_attributes_for
:
class Person < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address, allow_destroy: true
end
Now, when you use a form element with the _destroy
parameter, with a value that evaluates to true
, you will destroy the associated model (e.g. 1, ‘1’, true, or ‘true’):
<%= form_with model: @person do |person_form| %>
...
<%= person_form.fields_for :address do |address_fields| %>
...
Delete: <%= address_fields.check_box :_destroy %>
<% end %>
...
<% end %>
One-to-many
Consider a Person class which returns an array of Project instances from the projects
reader method and responds to the projects_attributes=
writer method:
class Person
def projects
[@project1, @project2]
end
def projects_attributes=(attributes)
# Process the attributes hash
end
end
Note that the projects_attributes=
writer method is in fact required for fields_for to correctly identify :projects
as a collection, and the correct indices to be set in the form markup.
When projects is already an association on Person you can use accepts_nested_attributes_for
to define the writer method for you:
class Person < ActiveRecord::Base
has_many :projects
accepts_nested_attributes_for :projects
end
This model can now be used with a nested fields_for. The block given to the nested fields_for call will be repeated for each instance in the collection:
<%= form_with model: @person do |person_form| %>
...
<%= person_form.fields_for :projects do |project_fields| %>
<% if project_fields.object.active? %>
Name: <%= project_fields.text_field :name %>
<% end %>
<% end %>
...
<% end %>
It’s also possible to specify the instance to be used:
<%= form_with model: @person do |person_form| %>
...
<% @person.projects.each do |project| %>
<% if project.active? %>
<%= person_form.fields_for :projects, project do |project_fields| %>
Name: <%= project_fields.text_field :name %>
<% end %>
<% end %>
<% end %>
...
<% end %>
Or a collection to be used:
<%= form_with model: @person do |person_form| %>
...
<%= person_form.fields_for :projects, @active_projects do |project_fields| %>
Name: <%= project_fields.text_field :name %>
<% end %>
...
<% end %>
If you want to destroy any of the associated models through the form, you have to enable it first using the :allow_destroy
option for accepts_nested_attributes_for
:
class Person < ActiveRecord::Base
has_many :projects
accepts_nested_attributes_for :projects, allow_destroy: true
end
This will allow you to specify which models to destroy in the attributes hash by adding a form element for the _destroy
parameter with a value that evaluates to true
(e.g. 1, ‘1’, true, or ‘true’):
<%= form_with model: @person do |person_form| %>
...
<%= person_form.fields_for :projects do |project_fields| %>
Delete: <%= project_fields.check_box :_destroy %>
<% end %>
...
<% end %>
When a collection is used you might want to know the index of each object in the array. For this purpose, the index
method is available in the FormBuilder object.
<%= form_with model: @person do |person_form| %>
...
<%= person_form.fields_for :projects do |project_fields| %>
Project #<%= project_fields.index %>
...
<% end %>
...
<% end %>
Note that fields_for will automatically generate a hidden field to store the ID of the record. There are circumstances where this hidden field is not needed and you can pass include_id: false
to prevent fields_for from rendering it automatically.
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 |
# File 'lib/action_view/helpers/form_helper.rb', line 2290 def fields_for(record_name, record_object = nil, = nil, &block) , record_object = record_object, nil if .nil? && record_object.is_a?(Hash) && record_object. ||= {} [:builder] ||= [:builder] [:namespace] = [:namespace] [:parent_builder] = self case record_name when String, Symbol if nested_attributes_association?(record_name) return fields_for_with_nested_attributes(record_name, record_object, , block) end else record_object = @template._object_for_form_builder(record_name) record_name = model_name_from_record_or_class(record_object).param_key end object_name = @object_name index = if .has_key?(:index) [:index] elsif defined?(@auto_index) object_name = object_name.to_s.delete_suffix("[]") @auto_index end record_name = if index "#{object_name}[#{index}][#{record_name}]" elsif record_name.end_with?("[]") "#{object_name}[#{record_name[0..-3]}][#{record_object.id}]" else "#{object_name}[#{record_name}]" end [:child_index] = index @template.fields_for(record_name, record_object, , &block) end |
#file_field(method, options = {}) ⇒ Object
Returns a file upload input tag tailored for accessing a specified attribute (identified by method
) on an object assigned to the template (identified by object
). Additional options on the input tag can be passed as a hash with options
. These options will be tagged onto the HTML as an HTML element attribute as in the example shown.
Using this method inside a form_with
block will set the enclosing form’s encoding to multipart/form-data
.
Options
-
Creates standard HTML attributes for the tag.
-
:disabled
- If set to true, the user will not be able to use this input. -
:multiple
- If set to true, *in most updated browsers* the user will be allowed to select multiple files. -
:include_hidden
- Whenmultiple: true
andinclude_hidden: true
, the field will be prefixed with an<input type="hidden">
field with an empty value to support submitting an empty collection of files. Sinceinclude_hidden
will default toconfig.active_storage.multiple_file_field_include_hidden
if you don’t specifyinclude_hidden
, you will need to passinclude_hidden: false
to prevent submitting an empty collection of files when passingmultiple: true
. -
:accept
- If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
Examples
# Let's say that @user has avatar:
file_field(:avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />
# Let's say that @article has image:
file_field(:image, :multiple => true)
# => <input type="file" id="article_image" name="article[image][]" multiple="multiple" />
# Let's say that @article has attached:
file_field(:attached, accept: 'text/html')
# => <input accept="text/html" type="file" id="article_attached" name="article[attached]" />
# Let's say that @article has image:
file_field(:image, accept: 'image/png,image/gif,image/jpeg')
# => <input type="file" id="article_image" name="article[image]" accept="image/png,image/gif,image/jpeg" />
# Let's say that @attachment has file:
file_field(:file, class: 'file_input')
# => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
2557 2558 2559 2560 |
# File 'lib/action_view/helpers/form_helper.rb', line 2557 def file_field(method, = {}) self.multipart = true @template.file_field(@object_name, method, ()) end |
#grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
<%= form_for @city do |f| %>
<%= f.grouped_collection_select :country_id, @continents, :countries, :name, :id, :name %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
872 873 874 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 872 def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, = {}, = {}) @template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, (), @default_html_options.merge()) end |
#hidden_field(method, options = {}) ⇒ Object
Returns a hidden input tag tailored for accessing a specified attribute (identified by method
) on an object assigned to the template (identified by object
). Additional options on the input tag can be passed as a hash with options
. These options will be tagged onto the HTML as an HTML element attribute as in the example shown.
Examples
# Let's say that @signup.pass_confirm returns true:
hidden_field(:pass_confirm)
# => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="true" />
# Let's say that @article.tag_list returns "blog, ruby":
hidden_field(:tag_list)
# => <input type="hidden" id="article_tag_list" name="article[tag_list]" value="blog, ruby" />
# Let's say that @user.token returns "abcde":
hidden_field(:token)
# => <input type="hidden" id="user_token" name="user[token]" value="abcde" />
2518 2519 2520 2521 |
# File 'lib/action_view/helpers/form_helper.rb', line 2518 def hidden_field(method, = {}) @emitted_hidden_id = true if method == :id @template.hidden_field(@object_name, method, ()) end |
#id ⇒ Object
Generate an HTML id
attribute value.
return the <form>
element’s id
attribute.
<%= form_with model: @article do |f| %>
<%# ... %>
<% content_for :sticky_footer do %>
<%= form.button(form: f.id) %>
<% end %>
<% end %>
In the example above, the :sticky_footer
content area will exist outside of the <form>
element. By declaring the form
HTML attribute, we hint to the browser that the generated <button>
element should be treated as the <form>
element’s submit button, regardless of where it exists in the DOM.
1754 1755 1756 |
# File 'lib/action_view/helpers/form_helper.rb', line 1754 def id .dig(:html, :id) || [:id] end |
#label(method, text = nil, options = {}, &block) ⇒ Object
Returns a label tag tailored for labelling an input field for a specified attribute (identified by method
) on an object assigned to the template (identified by object
). The text of label will default to the attribute name unless a translation is found in the current I18n locale (through helpers.label.<modelname>.<attribute>
) or you specify it explicitly. Additional options on the label tag can be passed as a hash with options
. These options will be tagged onto the HTML as an HTML element attribute as in the example shown, except for the :value
option, which is designed to target labels for radio_button tags (where the value is used in the ID of the input tag).
Examples
label(:title)
# => <label for="article_title">Title</label>
You can localize your labels based on model and attribute names. For example you can define the following in your locale (e.g. en.yml)
helpers:
label:
article:
body: "Write your entire text here"
Which then will result in
label(:body)
# => <label for="article_body">Write your entire text here</label>
Localization can also be based purely on the translation of the attribute-name (if you are using ActiveRecord):
activerecord:
attributes:
article:
cost: "Total cost"
label(:cost)
# => <label for="article_cost">Total cost</label>
label(:title, "A short title")
# => <label for="article_title">A short title</label>
label(:title, "A short title", class: "title_label")
# => <label for="article_title" class="title_label">A short title</label>
label(:privacy, "Public Article", value: "public")
# => <label for="article_privacy_public">Public Article</label>
label(:cost) do |translation|
content_tag(:span, translation, class: "cost_label")
end
# => <label for="article_cost"><span class="cost_label">Total cost</span></label>
label(:cost) do |builder|
content_tag(:span, builder.translation, class: "cost_label")
end
# => <label for="article_cost"><span class="cost_label">Total cost</span></label>
label(:cost) do |builder|
content_tag(:span, builder.translation, class: [
"cost_label",
("error_label" if builder.object.errors.include?(:cost))
])
end
# => <label for="article_cost"><span class="cost_label error_label">Total cost</span></label>
label(:terms) do
raw('Accept <a href="/terms">Terms</a>.')
end
# => <label for="article_terms">Accept <a href="/terms">Terms</a>.</label>
2405 2406 2407 |
# File 'lib/action_view/helpers/form_helper.rb', line 2405 def label(method, text = nil, = {}, &block) @template.label(@object_name, method, text, (), &block) end |
#radio_button(method, tag_value, options = {}) ⇒ Object
Returns a radio button tag for accessing a specified attribute (identified by method
) on an object assigned to the template (identified by object
). If the current value of method
is tag_value
the radio button will be checked.
To force the radio button to be checked pass checked: true
in the options
hash. You may pass HTML options there as well.
# Let's say that @article.category returns "rails":
("category", "rails")
("category", "java")
# => <input type="radio" id="article_category_rails" name="article[category]" value="rails" checked="checked" />
# <input type="radio" id="article_category_java" name="article[category]" value="java" />
# Let's say that @user.receive_newsletter returns "no":
("receive_newsletter", "yes")
("receive_newsletter", "no")
# => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
# <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
2496 2497 2498 |
# File 'lib/action_view/helpers/form_helper.rb', line 2496 def (method, tag_value, = {}) @template.(@object_name, method, tag_value, ()) end |
#select(method, choices = nil, options = {}, html_options = {}, &block) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:
<%= form_for @post do |f| %>
<%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
848 849 850 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 848 def select(method, choices = nil, = {}, = {}, &block) @template.select(@object_name, method, choices, (), @default_html_options.merge(), &block) end |
#self ⇒ Object
:method: range_field
:call-seq: range_field(method, options = {})
Wraps ActionView::Helpers::FormHelper#range_field for form builders:
<%= form_with model: @user do |f| %>
<%= f.range_field :age %>
<% end %>
Please refer to the documentation of the base helper for details.
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 |
# File 'lib/action_view/helpers/form_helper.rb', line 2021 ActiveSupport::CodeGenerator.batch(self, __FILE__, __LINE__) do |code_generator| (field_helpers - [:label, :check_box, :radio_button, :fields_for, :fields, :hidden_field, :file_field]).each do |selector| code_generator.define_cached_method(selector, namespace: :form_builder) do |batch| batch.push <<-RUBY_EVAL def #{selector}(method, options = {}) # def text_field(method, options = {}) @template.public_send( # @template.public_send( #{selector.inspect}, # :text_field, @object_name, # @object_name, method, # method, objectify_options(options)) # objectify_options(options)) end # end RUBY_EVAL end end end |
#submit(value = nil, options = {}) ⇒ Object
Add the submit button for the given form. When no value is given, it checks if the object is a new resource or not to create the proper label:
<%= form_with model: @article do |f| %>
<%= f.submit %>
<% end %>
In the example above, if @article
is a new record, it will use “Create Article” as submit button label; otherwise, it uses “Update Article”.
Those labels can be customized using I18n under the helpers.submit
key and using %{model}
for translation interpolation:
en:
helpers:
submit:
create: "Create a %{model}"
update: "Confirm changes to %{model}"
It also searches for a key specific to the given object:
en:
helpers:
submit:
article:
create: "Add %{model}"
2589 2590 2591 2592 2593 |
# File 'lib/action_view/helpers/form_helper.rb', line 2589 def submit(value = nil, = {}) value, = nil, value if value.is_a?(Hash) value ||= submit_default_value @template.submit_tag(value, ) end |
#time_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::DateHelper#time_select for form builders:
<%= form_for @race do |f| %>
<%= f.time_select :average_lap %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
1249 1250 1251 |
# File 'lib/action_view/helpers/date_helper.rb', line 1249 def time_select(method, = {}, = {}) @template.time_select(@object_name, method, (), ) end |
#time_zone_select(method, priority_zones = nil, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
<%= form_for @user do |f| %>
<%= f.time_zone_select :time_zone, nil, include_blank: true %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
884 885 886 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 884 def time_zone_select(method, priority_zones = nil, = {}, = {}) @template.time_zone_select(@object_name, method, priority_zones, (), @default_html_options.merge()) end |
#to_model ⇒ Object
1713 1714 1715 |
# File 'lib/action_view/helpers/form_helper.rb', line 1713 def to_model self end |
#to_partial_path ⇒ Object
1709 1710 1711 |
# File 'lib/action_view/helpers/form_helper.rb', line 1709 def to_partial_path self.class._to_partial_path end |
#weekday_select(method, options = {}, html_options = {}) ⇒ Object
Wraps ActionView::Helpers::FormOptionsHelper#weekday_select for form builders:
<%= form_for @user do |f| %>
<%= f.weekday_select :weekday, include_blank: true %>
<%= f.submit %>
<% end %>
Please refer to the documentation of the base helper for details.
896 897 898 |
# File 'lib/action_view/helpers/form_options_helper.rb', line 896 def weekday_select(method, = {}, = {}) @template.weekday_select(@object_name, method, (), @default_html_options.merge()) end |