0

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() 
am-rails
  • 1,463
  • 2
  • 16
  • 40
  • Is it a typo in the code here that you have `@survey = survey.build`? Shouldn't it be `@survey = Survey.new`? Where is your jQuery code? in the asset pipeline? – grumpit Jul 31 '12 at 03:37
  • Also, there is a repo on github that has that example: https://github.com/ryanb/complex-form-examples check the jQuery branch – grumpit Jul 31 '12 at 03:41
  • @grumpit, fixed it, i had edited it slightly from my actual code. – am-rails Jul 31 '12 at 04:11
  • the jquery code is in app/assets and the delete function there works fine. – am-rails Jul 31 '12 at 04:12
  • i'd update your jQuery with the example in the github repo on the jQuery branch - it's a bit different. see if that works... – grumpit Jul 31 '12 at 19:42

0 Answers0