Rails - Railscasts nested complex forms

夙愿已清 提交于 2020-01-06 14:33:48

问题


I am using Ryan Bates' Complex Forms Deep Branch, and trying to replicate that example for a form that has two additional nested levels.

SurveyName has many SurveyQuestions, which have many SurveyOptions.

# application_helper (identical to deep branch)
def remove_child_link(name, f)  
  f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")  
end

def add_child_link(name, f, method)  
  fields = new_child_fields(f, method)  
  link_to_function(name, h("insert_fields(this, \"#{method}\", \"#  {escape_javascript(fields)}\")"))
end  

def new_child_fields(form_builder, method, options = {})  
  options[:object] ||= form_builder.object.class.reflect_on_association(method).klass.new  
  options[:partial] ||= method.to_s.singularize  
  options[:form_builder_local] ||= :f  
  form_builder.fields_for(method, options[:object], :child_index => "new_#{method}") do |f|  
    render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })  
  end  
end

# application.js (identical to deep branch)
function insert_fields(link, method, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + method, "g")
  $(link).up().insert({
    before: content.replace(regexp, new_id)
  });
}
function remove_fields(link) {
  var hidden_field = $(link).previous("input[type=hidden]");
  if (hidden_field) {
    hidden_field.value = '1';
  }
  $(link).up(".fields").hide();
}

In Deep Branch, Project has many tasks, which have many assignments. My _task.html.erb equivalent is:

<div class="fields">
  <%= remove_child_link "remove", f %> 
  <%= f.fields_for :survey_options do |survey_option_form| %>
    <%= render :partial => "survey_option", :locals => { :f => survey_option_form } %>
  <% end %>
  # the above works
  <%= add_child_link "Add Option", f, :survey_options %>
  # the above line does NOT work
</div>

I hope I've given enough information. It is mystifying to me that with the same helper code the add_child_link function wouldn't work. Can you see what I'm missing?


回答1:


You have not added the javascript code in your application.js.



来源:https://stackoverflow.com/questions/4232367/rails-railscasts-nested-complex-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!