试图扩展ActionView :: Helpers :: FormBuilder

时间:2010-03-19 07:05:34

标签: ruby-on-rails actionview formbuilder

我试图通过将一些逻辑移入FormBuilder来干掉一些代码。在阅读了有关如何选择和替代表单构建器的文档后,对我来说逻辑解决方案似乎是这样的。

在视图中

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

然后在app / helpers / application_helper.rb

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

然而,这在“form_for”

中给我一个错误
  uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder

我在哪里做错了?

3 个答案:

答案 0 :(得分:5)

尝试:

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

答案 1 :(得分:4)

Builder类可以放在模块文件中,内部或/和模块定义之外,如下所示:

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

将构建器附加到表单的正确方法是:

    # 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|

以下是在表单上设置构建器选项的辅助方法:

    # 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
    ...

现在,有可选的方法将构建器附加到表单:

    # 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|

最后,自定义构建器可以放在单独的文件夹中,例如“app / builders”,但这需要手动将此路径添加到应用程序环境中。对于Rails 2.3.x,请设置:

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

答案 2 :(得分:4)

正如您在http://guides.rubyonrails.org/configuring.html#configuring-action-view中所看到的,您可以为整个应用程序设置默认的 FormBuilder 类。在你的情况下:

config.action_view.default_form_builder = "ApplicationHelper::TestFormBuilder"