我正在使用来自Railscast 197的嵌套模型表单技术(ASCIIcast here)。但我遇到了我的设置问题,我需要为我的一个嵌套模型的部分使用自定义表单构建器。我通过修改link_to_add_fields_helper来实现它,就像这样......
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}", :builder => AnswerFormBuilder) do |builder|
#was...
#fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
所以你看到设置两个嵌套模型的AnswerFormBuilder我解决了我的问题,但它不是很优雅,因为问题和答案都不需要它们。另外,我已经达到了我想要做一个Application wide form builder的地步。这让我想到了第二个问题,我如何“嵌套”自定义表单构建器?即让AnswerFormBuilder实现ApplicationFormBuilder将拥有的所有方法,以及Answers的其他一些特殊方法。非常感谢,我到处寻找并在其他博客上询问但尚无答案。
答案 0 :(得分:1)
所以几个月后我才知道......
def link_to_add_fields(name, f, association, options = {})
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}", :builder => options[:builder]) do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
然后,当我需要自定义表单构建器时,我只需使用key:builder和特定构建器的值调用传递link_to_add_fields哈希。
link_to_add_fields "Add Question", f, :questions, :builder => QuestionFormBuilder
如果没有散列(或no:构建器键值对)传递给link_add_fields,则fields_for方法默认为常规表单构建器。