Problem with Railscast #197 - Nested Model Form Part 2

Posted by sscirrus on Stack Overflow See other posts from Stack Overflow or by sscirrus
Published on 2010-06-18T01:49:40Z Indexed on 2010/06/18 1:53 UTC
Read the original article Hit count: 289

I'm trying to implement Ryan's Railscast #197 in a system with Questions, Answers, and (multiple choice) Options. http://railscasts.com/episodes/197-nested-model-form-part-2.

  • I have successfully implemented the nesting among these forms/partials.
  • The simpler 'check box' way to delete records works properly.
  • The problem occurs when I try to add/delete records.

I have copied the code exactly as it appears in his Railscast:

#new.html.erb
<%= javascript_include_tag :defaults, :cache => true %>
<% f.fields_for :in_options do |builder| %>
  <%= render "option_fields", :f => builder %>
<% end %>

#_option_fields.html.erb partial
<%= f.hidden_field :_destroy %>
<%= link_to_function "remove", "remove_fields(this)" %>

#application_helper.rb (exact same as #197)
  def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
  end

  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

#application.js (exact same as #197. I have an Event.addbehavior below this code.)
function remove_fields(link) {
  $(link).previous("input[type=hidden]").value = "1";
  $(link).up(".fields").hide();  
}

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)
  });
}

2 problems:

  • When I click on the 'remove' link it doesn't remove - it just shifts the page up or down.
  • When I include link_to_add_fields "Add Answer", f, :answers, I get undefined method `klass' for nil:NilClass.

Thanks everyone.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about ruby-on-rails