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 )