在 Ruby on Rails 中使用带有嵌套模型的自定义表单构建器
我正在使用 Railscast 197 (ASCIIcast 此处)。但我的设置遇到了问题,我需要为我的嵌套模型的部分之一使用自定义表单生成器。我已经通过修改 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 我有点解决了我的问题,但它不是很优雅,因为问题和答案都不需要他们。此外,我已经达到了我想做一个应用程序范围的表单生成器的地步。这引出了我的第二个问题,如何“嵌套”自定义表单生成器?即让 AnswerFormBuilder 实现 ApplicationFormBuilder 具有的所有方法,以及一些其他特殊的答案方法。非常感谢,我到处查看并在其他博客上询问,但还没有答案。
I'm using nested model form technique from Railscast 197 (ASCIIcast here). But I'm running into a problem with my setup, I need to use a custom form builder for one of my nested models' partials. I've got it working, sort of, by modifiying the link_to_add_fields_helper, like so...
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
So you see by setting both nested models the AnswerFormBuilder I kinda solved my problem, but it's not very elegant since both Questions and Answers don't need them. Additionally I've gotten to a point where I'd like to do an Application wide form builder. Which brings me to my second question, how can I "nest" custom form builders? I.e. have AnswerFormBuilder implement all the methods that the ApplicationFormBuilder would have, plus some other special ones for Answers. Thanks so much, I've looked everywhere and asked on other blogs but no answer yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以几个月后我想通了......
然后当我需要自定义表单生成器时,我只需调用传递 link_to_add_fields 一个带有键 :builder 和特定生成器值的哈希值。
如果没有哈希(或没有 :builder 键值对)传递给 link_add_fields,则 fields_for 方法默认为常规表单构建器。
So I figured it out months later...
Then when I when I need a custom form builder I just call pass link_to_add_fields a hash with the key :builder and value of the specific builder.
If no hash (or no :builder key value pair) is passed to link_add_fields the fields_for method defaults to the regular form builder.