开发者

Nested Model Form - dynamically adding/removing fields

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:

# he开发者_如何学Clpers/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 :)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜