Custom form helpers

前端 未结 3 1683
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 01:12

Is there a way that I can create a custom form helper so that instead of:

special_field_tag :object, :method

I can achieve something like:<

3条回答
  •  Happy的楠姐
    2020-12-08 01:50

    @Tilendor, thanks so much for the pointers. Here is an example of an enum_select form tag helper that uses Rails 4.1 enums to automatically populate the options of a select tag:

    # helpers/application_helper.rb
    module ApplicationHelper
      class ActionView::Helpers::FormBuilder
        # http://stackoverflow.com/a/2625727/1935918
        include ActionView::Helpers::FormTagHelper
        include ActionView::Helpers::FormOptionsHelper
        def enum_select(name, options = {})
          # select_tag "company[time_zone]", options_for_select(Company.time_zones
          #   .map { |value| [value[0].titleize, value[0]] }, selected: company.time_zone)
          select_tag @object_name + "[#{name}]", options_for_select(@object.class.send(name.to_s.pluralize)
            .map { |value| [value[0].titleize, value[0]] }, selected: @object.send(name))
        end
      end
    end
    

    The trickiest construct is @object.class.send(name.to_s.pluralize) which produces a hash of available values (e.g., Company.time_zones). Putting it in helpers/application_helper.rb makes it automatically available. It is used like:

    <%= f.label :billing_status %>:
    <%= f.enum_select :billing_status %>

提交回复
热议问题