嗨,我已经通过 Railscast 196 和 197 并且一切正常,但是我有一个关于扩展功能的问题。
在 Railscast 196 和 197 ( http://railscasts.com/episodes/197-nested-model-form-part-2 ) 结尾处,Ryan 添加了一个问题,然后分别添加了答案。我要实现的是在添加问题时自动添加答案。
这是项目代码:http ://railscasts.com/episodes/196-nested-model-form-revised (如果您没有订阅,则为旧版本:http ://railscasts.com/episodes/197-嵌套模型形式第 2 部分)
评论部分中有一条评论建议将该行child_object = f.object.class.reflect_on_association(association).klass.reflect_on_association(child_association).klass.new
添加到帮助程序中以完成此操作,但是当我实现此操作时出现错误:
undefined method 'klass' for nil:NilClass
编辑:需要明确的是,在尝试构建child_object
. 将new_object
正确构建和渲染。
我的修改助手
def link_to_add_fields(name, f, association, container, child_association)
new_object = f.object.class.reflect_on_association(association).klass.new
child_object = f.object.class.reflect_on_association(association).klass.reflect_on_association(child_association).klass.new
new_object.answers = child_object
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s + "/" + association.to_s.singularize + "_fields", :f => builder)
end
link_to name, "#", class: "add-fields", data: { container: "#{container}", association: "#{association}", content: "#{fields}" }
end
呼叫帮手
= form_for @survey, :html => { :multipart => true } do |f|
%fieldset
%legend
Questions
#questions.nested
= f.fields_for :questions do |question|
= render 'questions/question_fields', :f => question
= link_to_add_fields "Add Question", f, :questions, "questions", :image