【问题标题】:Adding custom field in rails form helper在 Rails 表单助手中添加自定义字段
【发布时间】:2017-08-08 21:26:15
【问题描述】:

我正在使用 rails 应用程序,对于国家/地区和城市选择字段,我想创建一个自定义字段,以便以后可以将其用作已存在的字段。

例如

f.country_select :country 

上面的字段应该会自动生成一个带有国家列表的选择。

I want three fields country, state and city so connected that when country field selected state select field gets state list and when state is selected city select works same.

感谢您的宝贵回答。

【问题讨论】:

    标签: ruby-on-rails field helper


    【解决方案1】:

    为此,您应该从 here 开始。在此 rails cast 中,您可以了解如何根据父 (Country) 选择动态填充子 (State) 选择框中的数据。 您需要为城市扩展功能。

    但在给定的教程中,您应该有国家和州的数据。要管理这些数据,您可以使用City-State

    在教程中使用Country.find(:all),所以你需要将其更改为CS.get。对于选定国家/地区的状态,例如CS.get :us

    希望这行得通。

    【讨论】:

      【解决方案2】:

      是的,您可以将此方法添加到ActionView::Helpers::FormBuilder 类 这是

      的例子
      class ActionView::Helpers::FormBuilder
        def error_message_on(method, options = {})
          @template.error_message_on(@object_name, method, objectify_options(options))
        end
      end
      

      然后你就可以这样做了

      = f.label :description, I18n.t(:description)
      = f.text_field :description, class: 'form-control'
      = f.error_message_on :description
      

      【讨论】:

        【解决方案3】:

        您可以使用 gem city-state github gem link

        【讨论】:

          猜你喜欢
          • 2014-04-07
          • 2017-11-07
          • 1970-01-01
          • 2011-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-22
          相关资源
          最近更新 更多