Action View Form Builder¶↑
AFormBuilder object is associated with a particular model object and allows you to generate fields associated with the model object. TheFormBuilder object is yielded when usingform_with orfields_for. For example:
<%= form_with model: @person do |person_form| %> Name: <%= person_form.text_field :name %> Admin: <%= person_form.checkbox :admin %><% end %>
In the above block, aFormBuilder object is yielded as theperson_form variable. This allows you to generate thetext_field andcheckbox fields by specifying their eponymous methods, which modify the underlying template and associates the@person model object with the form.
TheFormBuilder object can be thought of as serving as a proxy for the methods in theFormHelper module. This class, however, allows you to call methods with the model object you are building the form for.
You can create your own customFormBuilder templates by subclassing this class. For example:
classMyFormBuilder<ActionView::Helpers::FormBuilderdefdiv_radio_button(method,tag_value,options = {})@template.content_tag(:div,@template.radio_button(@object_name,method,tag_value,objectify_options(options) ) )endend
The above code creates a new methoddiv_radio_button which wraps a div around the new radio button. Note that when options are passed in, you must callobjectify_options in order for the model object to get correctly passed to the method. Ifobjectify_options is not called, then the newly created helper will not be linked back to the model.
Thediv_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 thefield_helpers class attribute.
- #
- B
- C
- D
- E
- F
- G
- H
- I
- L
- M
- N
- P
- R
- S
- T
- U
- W
Attributes
| [R] | index | |
| [R] | multipart | |
| [R] | multipart? | |
| [RW] | object | |
| [RW] | object_name | |
| [RW] | options |
Class Public methods
_to_partial_path()Link
new(object_name, object, template, options)Link
# File actionview/lib/action_view/helpers/form_helper.rb, line 1720definitialize(object_name,object,template,options)@nested_child_index = {}@object_name,@object,@template,@options =object_name,object,template,options@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)convert_to_legacy_options(@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_paramelseraiseArgumentError,"object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"endend@multipart =nil@index =options[:index]||options[:child_index]end
Instance Public methods
button(value = nil, options = {}, &block)Link
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 thehelpers.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¶↑
button("Create article")# => <button name='button' type='submit'>Create article</button>button(:draft,value:true)# => <button id="article_draft" name="article[draft]" value="true" type="submit">Create article</button>buttondocontent_tag(:strong,'Ask me!')end# => <button name='button' type='submit'># <strong>Ask me!</strong># </button>buttondo|text|content_tag(:strong,text)end# => <button name='button' type='submit'># <strong>Create article</strong># </button>button(:draft,value:true)docontent_tag(:strong,"Save as draft")end# => <button id="article_draft" name="article[draft]" value="true" type="submit"># <strong>Save as draft</strong># </button>
# File actionview/lib/action_view/helpers/form_helper.rb, line 2649defbutton(value =nil,options = {},&block)casevaluewhenHashvalue,options =nil,valuewhenSymbolvalue,options =nil, {name:field_name(value),id:field_id(value) }.merge!(options.to_h)endvalue||=submit_default_valueifblock_given?value =@template.capture {yield(value) }endformmethod =options[:formmethod]ifformmethod.present?&&!/post|get/i.match?(formmethod)&&!options.key?(:name)&&!options.key?(:value)options.merge!formmethod::post,name:"_method",value:formmethodend@template.button_tag(value,options)end
checkbox(method, options = {}, checked_value = "1", unchecked_value = "0")Link
Returns a checkbox tag tailored for accessing a specified attribute (identified bymethod) on an object assigned to the template (identified byobject). This object must be an instance object (@object) and not a local object. It’s intended thatmethod 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 withoptions. Thechecked_value defaults to 1 while the defaultunchecked_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-trueorfalseforces 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 anInvoice model has apaid flag, and in the form that edits a paid invoice the user unchecks its check box, nopaid 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.checkbox :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 useFormTagHelper#checkbox_tag or to use hashes instead of arrays.
Examples¶↑
# Let's say that @article.validated? is 1:checkbox("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":checkbox("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":checkbox("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" />
collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)Link
collection_checkboxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)Link
WrapsActionView::Helpers::FormOptionsHelper#collection_checkboxes for form builders:
<%= form_with model: @post do |f| %> <%= f.collection_checkboxes :author_ids, Author.all, :id, :name_with_initial %> <%= f.submit %><% end %>
Please refer to the documentation of the base helper for details.
# File actionview/lib/action_view/helpers/form_options_helper.rb, line 911defcollection_checkboxes(method,collection,value_method,text_method,options = {},html_options = {},&block)@template.collection_checkboxes(@object_name,method,collection,value_method,text_method,objectify_options(options),@default_html_options.merge(html_options),&block)end
collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)Link
WrapsActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
<%= form_with model: @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.
# File actionview/lib/action_view/helpers/form_options_helper.rb, line 924defcollection_radio_buttons(method,collection,value_method,text_method,options = {},html_options = {},&block)@template.collection_radio_buttons(@object_name,method,collection,value_method,text_method,objectify_options(options),@default_html_options.merge(html_options),&block)end
collection_select(method, collection, value_method, text_method, options = {}, html_options = {})Link
WrapsActionView::Helpers::FormOptionsHelper#collection_select for form builders:
<%= form_with model: @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.
# File actionview/lib/action_view/helpers/form_options_helper.rb, line 863defcollection_select(method,collection,value_method,text_method,options = {},html_options = {})@template.collection_select(@object_name,method,collection,value_method,text_method,objectify_options(options),@default_html_options.merge(html_options))end
color_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#color_field for form builders:
<%= form_with model: @user do |f| %> <%= f.color_field :favorite_color %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1843date_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#date_field for form builders:
<%= form_with model: @user do |f| %> <%= f.date_field :born_on %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1895date_select(method, options = {}, html_options = {})Link
WrapsActionView::Helpers::DateHelper#date_select for form builders:
<%= form_with model: @person do |f| %> <%= f.date_select :birth_date %> <%= f.submit %><% end %>
Please refer to the documentation of the base helper for details.
datetime_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#datetime_field for form builders:
<%= form_with model: @user do |f| %> <%= f.datetime_field :graduation_day %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1921datetime_local_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#datetime_local_field for form builders:
<%= form_with model: @user do |f| %> <%= f.datetime_local_field :graduation_day %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1934datetime_select(method, options = {}, html_options = {})Link
WrapsActionView::Helpers::DateHelper#datetime_select for form builders:
<%= form_with model: @person do |f| %> <%= f.datetime_select :last_request_at %> <%= f.submit %><% end %>
Please refer to the documentation of the base helper for details.
email_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#email_field for form builders:
<%= form_with model: @user do |f| %> <%= f.email_field :address %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1986field_id(method, *suffixes, namespace: @options[:namespace], index: @options[:index])Link
Generate an HTMLid attribute value for the given field
Return the value generated by theFormBuilder 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 totext_field declares anaria-describedby attribute referencing the<span> element, sharing a commonid root (article_title, in this case).
field_name(method, *methods, multiple: false, index: @options[:index])Link
Generate an HTMLname attribute value for the given name and field combination
Return the value generated by theFormBuilder 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 %>
fields(scope = nil, model: nil, **options, &block)Link
See the docs for theActionView::Helpers::FormHelper#fields helper method.
# File actionview/lib/action_view/helpers/form_helper.rb, line 2327deffields(scope =nil,model:nil,**options,&block)options[:allow_method_names_outside_object] =trueoptions[:skip_default_ids] =!FormHelper.form_with_generates_idsconvert_to_legacy_options(options)fields_for(scope||model,model,options,&block)end
fields_for(record_name, record_object = nil, fields_options = nil, &block)Link
Creates a scope around a specific model object like form_with, but doesn’t create the form tags themselves. This makesfields_for suitable for specifying additional model objects in the same form.
Although the usage and purpose offields_for is similar to form_with’s, its method signature is slightly different. Like form_with, it yields aFormBuilder 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 theparams 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.checkbox :admin %> <% end %> <%= person_form.submit %><% end %>
In this case, the checkbox field will be represented by an HTMLinput tag with thename attributepermission[admin], and the submitted value will appear in the controller asparams[:permission][:admin]. If@person.permission is an existing record with an attributeadmin, 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 tofields_for -
<%= fields_for :permission do |permission_fields| %> Admin?: <%= permission_fields.checkbox :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 symbolfields_for will realize that the name has been omitted) -
<%= fields_for @person.permission do |permission_fields| %> Admin?: <%= permission_fields.checkbox :admin %><% end %>
andfields_for will derive the required name of the field from theclass of the model object, e.g. if@person.permission, is of classPermission, the field will still be namedpermission[admin].
Note: This also works for the methods inFormOptionsHelper andDateHelper that are designed to work with an object as base, likeFormOptionsHelper#collection_select andDateHelper#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 optionHash. To remove the ambiguity, explicitly pass an optionHash, even if empty.
<%= form_with model: @person do |person_form| %> ... <%= fields_for :permission, @person.permission, {} do |permission_fields| %> Admin?: <%= checkbox_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 withaccepts_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 calledaddress_attributes=.
Whether a one-to-one or one-to-many style form builder will be yielded depends on whether the normal reader method returns asingle object or anarray of objects.
One-to-one¶↑
Consider a Person class which returns asingle Address from theaddress reader method and responds to theaddress_attributes= writer method:
classPersondefaddress@addressenddefaddress_attributes=(attributes)# Process the attributes hashendend
This model can now be used with a nestedfields_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 useaccepts_nested_attributes_for to define the writer method for you:
classPerson<ActiveRecord::Basehas_one:addressaccepts_nested_attributes_for:addressend
If you want to destroy the associated model through the form, you have to enable it first using the:allow_destroy option foraccepts_nested_attributes_for:
classPerson<ActiveRecord::Basehas_one:addressaccepts_nested_attributes_for:address,allow_destroy:trueend
Now, when you use a form element with the_destroy parameter, with a value that evaluates totrue, 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.checkbox :_destroy %> <% end %> ...<% end %>
One-to-many¶↑
Consider a Person class which returns anarray of Project instances from theprojects reader method and responds to theprojects_attributes= writer method:
classPersondefprojects [@project1,@project2]enddefprojects_attributes=(attributes)# Process the attributes hashendend
Note that theprojects_attributes= writer method is in fact required forfields_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 useaccepts_nested_attributes_for to define the writer method for you:
classPerson<ActiveRecord::Basehas_many:projectsaccepts_nested_attributes_for:projectsend
This model can now be used with a nestedfields_for. The block given to the nestedfields_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 foraccepts_nested_attributes_for:
classPerson<ActiveRecord::Basehas_many:projectsaccepts_nested_attributes_for:projects,allow_destroy:trueend
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 totrue (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.checkbox :_destroy %> <% end %> ...<% end %>
When a collection is used you might want to know the index of each object in the array. For this purpose, theindex method is available in theFormBuilder object.
<%= form_with model: @person do |person_form| %> ... <%= person_form.fields_for :projects do |project_fields| %> Project #<%= project_fields.index %> ... <% end %> ...<% end %>
Note thatfields_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 passinclude_id: false to preventfields_for from rendering it automatically.
# File actionview/lib/action_view/helpers/form_helper.rb, line 2289deffields_for(record_name,record_object =nil,fields_options =nil,&block)fields_options,record_object =record_object,niliffields_options.nil?&&record_object.is_a?(Hash)&&record_object.extractable_options?fields_options||= {}fields_options[:builder]||=options[:builder]fields_options[:namespace] =options[:namespace]fields_options[:parent_builder] =selfcaserecord_namewhenString,Symbolifnested_attributes_association?(record_name)returnfields_for_with_nested_attributes(record_name,record_object,fields_options,block)endelserecord_object =@template._object_for_form_builder(record_name)record_name =model_name_from_record_or_class(record_object).param_keyendobject_name =@object_nameindex =ifoptions.has_key?(:index)options[:index]elsifdefined?(@auto_index)object_name =object_name.to_s.delete_suffix("[]")@auto_indexendrecord_name =ifindex"#{object_name}[#{index}][#{record_name}]"elsifrecord_name.end_with?("[]")"#{object_name}[#{record_name[0..-3]}][#{record_object.id}]"else"#{object_name}[#{record_name}]"endfields_options[:child_index] =index@template.fields_for(record_name,record_object,fields_options,&block)end
file_field(method, options = {})Link
Returns a file upload input tag tailored for accessing a specified attribute (identified bymethod) on an object assigned to the template (identified byobject). Additional options on the input tag can be passed as a hash withoptions. 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 tomultipart/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: trueandinclude_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_hiddenwill default toconfig.active_storage.multiple_file_field_include_hiddenif you don’t specifyinclude_hidden, you will need to passinclude_hidden: falseto 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" />
grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})Link
WrapsActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
<%= form_with model: @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.
# File actionview/lib/action_view/helpers/form_options_helper.rb, line 875defgrouped_collection_select(method,collection,group_method,group_label_method,option_key_method,option_value_method,options = {},html_options = {})@template.grouped_collection_select(@object_name,method,collection,group_method,group_label_method,option_key_method,option_value_method,objectify_options(options),@default_html_options.merge(html_options))end
hidden_field(method, options = {})Link
Returns a hidden input tag tailored for accessing a specified attribute (identified bymethod) on an object assigned to the template (identified byobject). Additional options on the input tag can be passed as a hash withoptions. 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" />
id()Link
Generate an HTMLid attribute value.
return the<form> element’sid 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 theform 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.
label(method, text = nil, options = {}, &block)Link
Returns a label tag tailored for labelling an input field for a specified attribute (identified bymethod) on an object assigned to the template (identified byobject). The text of label will default to the attribute name unless a translation is found in the current I18n locale (throughhelpers.label.<modelname>.<attribute>) or you specify it explicitly. Additional options on the label tag can be passed as a hash withoptions. 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 forradio_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 usingActiveRecord):
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"ifbuilder.object.errors.include?(:cost)) ])end# => <label for="article_cost"><span class="cost_label error_label">Total cost</span></label>label(:terms)doraw('Accept <a href="/terms">Terms</a>.')end# => <label for="article_terms">Accept <a href="/terms">Terms</a>.</label>
month_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#month_field for form builders:
<%= form_with model: @user do |f| %> <%= f.month_field :birthday_month %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1947multipart=(multipart)Link
number_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#number_field for form builders:
<%= form_with model: @user do |f| %> <%= f.number_field :age %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1999password_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#password_field for form builders:
<%= form_with model: @user do |f| %> <%= f.password_field :password %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1817phone_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#phone_field for form builders:
<%= form_with model: @user do |f| %> <%= f.phone_field :phone %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1882radio_button(method, tag_value, options = {})Link
Returns a radio button tag for accessing a specified attribute (identified bymethod) on an object assigned to the template (identified byobject). If the current value ofmethod istag_value the radio button will be checked.
To force the radio button to be checked passchecked: true in theoptions hash. You may pass HTML options there as well.
# Let's say that @article.category returns "rails":radio_button("category","rails")radio_button("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":radio_button("receive_newsletter","yes")radio_button("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" />
range_field(method, options = {})Link
WrapsActionView::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.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 2012rich_text_area(method, options = {}, &block)Link
rich_textarea(method, options = {}, &block)Link
WrapsActionView::Helpers::FormHelper#rich_textarea for form builders:
<%= form_with model: @message do |f| %> <%= f.rich_textarea :content %><% end %>
Please refer to the documentation of the base helper for details.
search_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#search_field for form builders:
<%= form_with model: @user do |f| %> <%= f.search_field :name %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1856select(method, choices = nil, options = {}, html_options = {}, &block)Link
WrapsActionView::Helpers::FormOptionsHelper#select for form builders:
<%= form_with model: @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.
submit(value = nil, options = {})Link
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 thehelpers.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}"telephone_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#telephone_field for form builders:
<%= form_with model: @user do |f| %> <%= f.telephone_field :phone %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1869text_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#text_field for form builders:
<%= form_with model: @user do |f| %> <%= f.text_field :name %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1804textarea(method, options = {})Link
WrapsActionView::Helpers::FormHelper#textarea for form builders:
<%= form_with model: @user do |f| %> <%= f.textarea :detail %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1830time_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#time_field for form builders:
<%= form_with model: @user do |f| %> <%= f.time_field :born_at %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1908time_select(method, options = {}, html_options = {})Link
WrapsActionView::Helpers::DateHelper#time_select for form builders:
<%= form_with model: @race do |f| %> <%= f.time_select :average_lap %> <%= f.submit %><% end %>
Please refer to the documentation of the base helper for details.
time_zone_select(method, priority_zones = nil, options = {}, html_options = {})Link
WrapsActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
<%= form_with model: @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.
# File actionview/lib/action_view/helpers/form_options_helper.rb, line 887deftime_zone_select(method,priority_zones =nil,options = {},html_options = {})@template.time_zone_select(@object_name,method,priority_zones,objectify_options(options),@default_html_options.merge(html_options))end
to_model()Link
to_partial_path()Link
url_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#url_field for form builders:
<%= form_with model: @user do |f| %> <%= f.url_field :homepage %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1973week_field(method, options = {})Link
WrapsActionView::Helpers::FormHelper#week_field for form builders:
<%= form_with model: @user do |f| %> <%= f.week_field :birthday_week %><% end %>
Please refer to the documentation of the base helper for details.
Source:on GitHub
# File actionview/lib/action_view/helpers/form_helper.rb, line 1960weekday_select(method, options = {}, html_options = {})Link
WrapsActionView::Helpers::FormOptionsHelper#weekday_select for form builders:
<%= form_with model: @user do |f| %> <%= f.weekday_select :weekday, include_blank: true %> <%= f.submit %><% end %>
Please refer to the documentation of the base helper for details.