3

我试图通过将一些逻辑移动到 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

我在哪里做错了?

4

3 回答 3

5

尝试:

form_for @event, :builder => ApplicationHelper::TestFormBuilder do |f|
于 2010-03-19T08:00:44.307 回答
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 )
于 2011-07-01T10:06:36.950 回答
4

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

config.action_view.default_form_builder = "ApplicationHelper::TestFormBuilder"
于 2012-03-02T13:47:11.353 回答