I followed the instructions on RailsCasts to setup a Nested Model Form. (This lets you have multiple models within one form.) The initial code did not work until I added code to controller new method to build the nested-models (see below). The second part was using ajax to add and delete fields.
The Ajax deletions worked to delete the answers, but not the ajax to add new answer fields. I think this is because I need to connect the ajax to the controller code, but I'm not sure how to do that.
This is the code I added to the controller:
def new
@survey = Survey.new
@question = @survey.questions.build
@question.answers.build
end
This is the other relevant code (from the railscast):
<%= link_to_add_fields "Add answer", f, :answers %>
That calls following method:
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
Which calls following jquery:
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()