Attempting to Extend ActionView :: Helpers :: FormBuilder

I am trying to dry some code by moving some logic to FormBuilder. After reading the documentation on how to choose and an alternative form builder, the logical solution for me seemed to be something like this.

In view

<% form_for @event, :builder => TestFormBuilder do |f| %> <%= f.test %> <%= f.submit 'Update' %> <% end %> 

and then in the application / helpers / application _helper.rb

 module ApplicationHelper class TestFormBuilder < ActionView::Helpers::FormBuilder def test puts 'apa' end end end 

This, however, gives me an error in the form of "form_for"

  uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder 

Where am I doing this wrong?

+2
source share
3 answers

try:

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

The Builder class can be placed in the module file, inside or / or outside the module, for example:

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

The correct way to attach a builder to a form:

  # 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 a helper method for setting the builder option on the 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 an additional way to bind the builder to the 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 collectors can be placed in a separate folder, for example, "app / builders", but this requires that you manually add this path to the application environment. For Rails 2.3.x, install:

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

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

 config.action_view.default_form_builder = "ApplicationHelper::TestFormBuilder" 
+4
source

All Articles