instance method range_field

Ruby on Rails edge

Since v6.0.6.1

Available in: v6.0.6.1 v6.1.7.10 v7.0.10 v7.1.6 v7.2.4 v8.0.5.1 v8.1.4 edge

Signature

range_field(method, options = {})

No documentation comment.

Parameters

method req
options opt = {}
Source
# File actionview/lib/action_view/helpers/form_helper.rb, line 2301
      def range_field(method, options = {}) = @template.range_field(@object_name, method, objectify_options(options))
      alias_method :text_area, :textarea

      # 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.checkbox :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.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 symbol `fields_for` will realize that the
      # name has been omitted) -
      #
      # ```
      # <%= fields_for @person.permission do |permission_fields| %>
      #   Admin?: <%= permission_fields.checkbox :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?: <%= 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
      # 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.checkbox :_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.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, 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.
      def fields_for(record_name, record_object = nil, fields_options = nil, &block)
        fields_options, record_object = record_object, nil if fields_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] = self

        case record_name
        when String, Symbol
          if nested_attributes_association?(record_name)
            return fields_for_with_nested_attributes(record_name, record_object, fields_options, 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 options.has_key?(:index)
          options[: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
        fields_options[:child_index] = index

        @template.fields_for(record_name, record_object, fields_options, &block)
      end

      # See the docs for the ActionView::Helpers::FormHelper#fields helper method.
      def fields(scope = nil, model: nil, **options, &block)
        options[:allow_method_names_outside_object] = true
        options[:skip_default_ids] = !FormHelper.form_with_generates_ids

        convert_to_legacy_options(options)

        fields_for(scope || model, model, options, &block)
      end

      # 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"
      # ```
      #
      # <code></code>
      #
      # ```
      # 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>
      # ```
      def label(method, text = nil, options = {}, &block)
        @template.label(@object_name, method, text, objectify_options(options), &block)
      end

      # 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` or `false` 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.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 use FormTagHelper#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" />
      # ```
      def checkbox(method, options = {}, checked_value = "1", unchecked_value = "0")
        @template.checkbox(@object_name, method, objectify_options(options), checked_value, unchecked_value)
      end
      alias_method :check_box, :checkbox

      # 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":
      # 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" />
      # ```
      def radio_button(method, tag_value, options = {})
        @template.radio_button(@object_name, method, tag_value, objectify_options(options))
      end

      # 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" />
      # ```
      #
      def hidden_field(method, options = {})
        @emitted_hidden_id = true if method == :id
        @template.hidden_field(@object_name, method, objectify_options(options))
      end

      # 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` - When `multiple: true` and `include_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. Since `include_hidden` will default to `config.active_storage.multiple_file_field_include_hidden` if you don't specify `include_hidden`, you will need to pass `include_hidden: false` to prevent submitting an empty collection of files when passing `multiple: 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" />
      # ```
      def file_field(method, options = {})
        self.multipart = true
        @template.file_field(@object_name, method, objectify_options(options))
      end

      # 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}"
      # ```
      #
      def submit(value = nil, options = {})
        value, options = nil, value if value.is_a?(Hash)
        value ||= submit_default_value
        @template.submit_tag(value, options)
      end

      # 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
      #
      # ```
      # 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>
      #
      # button do
      #   content_tag(:strong, 'Ask me!')
      # end
      # # => <button name="button" type="submit">
      # #      <strong>Ask me!</strong>
      # #    </button>
      #
      # button do |text|
      #   content_tag(:strong, text)
      # end
      # # => <button name="button" type="submit">
      # #      <strong>Create article</strong>
      # #    </button>
      #
      # 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>
      # ```
      #
      def button(value = nil, options = {}, &block)
        case value
        when Hash
          value, options = nil, value
        when Symbol
          value, options = nil, { name: field_name(value), id: field_id(value) }.merge!(options.to_h)
        end
        value ||= submit_default_value

        if block_given?
          value = @template.capture { yield(value) }
        end

        formmethod = options[:formmethod]
        if formmethod.present? && !/post|get/i.match?(formmethod) && !options.key?(:name) && !options.key?(:value)
          options.merge! formmethod: :post, name: "_method", value: formmethod
        end

        @template.button_tag(value, options)
      end

      def emitted_hidden_id? # :nodoc:
        @emitted_hidden_id ||= nil
      end

      private
        def objectify_options(options)
          result = @default_options.merge(options)
          result[:object] = @object
          result
        end

        def submit_default_value
          object = convert_to_model(@object)
          key    = object ? (object.persisted? ? :update : :create) : :submit

          model = if object.respond_to?(:model_name)
            object.model_name.human
          else
            @object_name.to_s.humanize
          end

          defaults = []
          # Object is a model and it is not overwritten by as and scope option.
          if object.respond_to?(:model_name) && object_name.to_s == model.downcase
            defaults << :"helpers.submit.#{object.model_name.i18n_key}.#{key}"
          else
            defaults << :"helpers.submit.#{object_name}.#{key}"
          end
          defaults << :"helpers.submit.#{key}"
          defaults << "#{key.name.humanize} #{model}"

          I18n.t(defaults.shift, model: model, default: defaults)
        end

        def nested_attributes_association?(association_name)
          @object.respond_to?("#{association_name}_attributes=")
        end

        def fields_for_with_nested_attributes(association_name, association, options, block)
          name = "#{object_name}[#{association_name}_attributes]"
          association = convert_to_model(association)

          if association.respond_to?(:persisted?)
            association = [association] if @object.public_send(association_name).respond_to?(:to_ary)
          elsif !association.respond_to?(:to_ary)
            association = @object.public_send(association_name)
          end

          if association.respond_to?(:to_ary)
            explicit_child_index = options[:child_index]
            output = ActiveSupport::SafeBuffer.new
            association.each do |child|
              if explicit_child_index
                options[:child_index] = explicit_child_index.call if explicit_child_index.respond_to?(:call)
              else
                options[:child_index] = nested_child_index(name)
              end
              if content = fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
                output << content
              end
            end
            output
          elsif association
            fields_for_nested_model(name, association, options, block)
          end
        end

        def fields_for_nested_model(name, object, fields_options, block)
          object = convert_to_model(object)
          emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) {
            options.fetch(:include_id, true)
          }

          @template.fields_for(name, object, fields_options) do |f|
            output = @template.capture(f, &block)
            output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id?
            output
          end
        end

        def nested_child_index(name)
          @nested_child_index[name] ||= -1
          @nested_child_index[name] += 1
        end

        def convert_to_legacy_options(options)
          if options.key?(:skip_id)
            options[:include_id] = !options.delete(:skip_id)
          end
        end
    end

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

Defined in ActionView::Helpers::FormBuilder

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close