0

I have been following the railscasts 'Nested Model Form Parts 1 & 2' about the survey form containing questions which in turn contain answers. The thing is that when the survey form is initially displayed, a question field, along with one answer field are displayed. When user clicks on the 'Add Question' field, only the question field is displayed. No answer field is displayed until user clicks on 'Add Answer'.

I would like both a question field and an answer field to be initially displayed when user clicks on 'Add Question'.

Currently the code is like this:

# helpers/application_helper.rb
module ApplicationHelper

  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}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
  end
end




// application.js

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).up().insert({
    before: content.replace(regexp, new_id)
  });
}

Any help will be much appreciated.

Thanks a lot :)

1 Answer 1

1

The render(association.to_s.singularize + "_fields", :f => builder) calls a partial that contains the question field . You should look for the _question_fields in view/questions/ directory and add an answer field there

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the suggestion but my '_question_fields' file does contain the following: <% f.fields_for :answers do |builder| %> <%= render 'answer_fields', :f => builder %> <% end %>
Yet, it's displaying the answer field only when the survey form is initially loaded. Clicking on the 'Add Question' link displays only the question field with a link to add an answer. What i want is to display the answer field at the same time as the question field itself when 'Add Question' link is clicked upon
<% f.fields_for :answers do |builder| %> <%= render 'answer_fields', :f => builder %> <% end %> will render all the answers associated to the upper Question. When you add a question make sure that question also has an answer question = Question.new - question. answers << Answer.new

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.