Hi I've gone though Railscast 196 & 197 and got everything working, however I have a question about extending the functionality.
At the end of Railscast 196 & 197 (http://railscasts.com/episodes/197-nested-model-form-part-2) Ryan adds a question and then adds answers individually. What I'm trying to implement is adding answers automatically when a question is added.
Here is the project code: http://railscasts.com/episodes/196-nested-model-form-revised (or an older version if you do not have a subscription: http://railscasts.com/episodes/197-nested-model-form-part-2)
There is a comment in the comments section that suggest that the line child_object = f.object.class.reflect_on_association(association).klass.reflect_on_association(child_association).klass.new
be added to the helper to accomplish this, however when I implement this I get the error:
undefined method 'klass' for nil:NilClass
EDIT: To be clear, it's failing with this error when trying to build the child_object
. The new_object
will build and render correctly.
My Modified helper
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
Call to helper
= 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