Trying to extend ActionView::Helpers::FormBuilder

大城市里の小女人 提交于 2019-12-01 09:10:29

try with :

form_for @event, :builder => ApplicationHelper::TestFormBuilder do |f|

Builder class can be placed in module file, inside or/and outside module definition, like this:

    # app/helpers/events_helper.rb
    module EventsHelper
        ...
        class FormBuilderIn < ActionView::Helpers::FormBuilder
            ...
        end
    end
    class FormBuilderOut < ActionView::Helpers::FormBuilder
        ...
    end

Proper way to attach builder to form is:

    # app/views/events/_form_in.html.erb
    form_for @event, :builder => EventsHelper::FormBuilderIn do |f|

    # app/views/events/_form_out.html.erb
    form_for @event, :builder => FormBuilderOut do |f|

Here is helper method for setting builder option on form:

    # app/helpers/events_helper.rb
    module EventsHelper
      def form_in_for(data, *args, &proc)
          options = args.extract_options!
          form_for(data, *(args << options.merge(:builder => EventsHelper::FormBuilderIn)), &proc)
      end
      def form_out_for(data, *args, &proc)
          options = args.extract_options!
          form_for(data, *(args << options.merge(:builder => FormBuilderOut)), &proc)
      end
    end
    ...

Now, there is optional way to attach builder to form:

    # app/views/events/_form_in.html.erb
    form_in_for @event do |f|

    # app/views/events/_form_out.html.erb
    form_out_for @event do |f|

Finally, custom builders can be placed in separated folder, for example "app/builders", but this demands to manually add this path into application environment. For Rails 2.3.x, set:

    # config/environment.rb.
    config.load_paths += %W( #{RAILS_ROOT}/app/builders )

As you can see in http://guides.rubyonrails.org/configuring.html#configuring-action-view, you can set a default FormBuilder-class for your whole application. In your case:

config.action_view.default_form_builder = "ApplicationHelper::TestFormBuilder"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!