Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8526557
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T08:18:20+00:00 2026-06-11T08:18:20+00:00

I’m having a rough go integrating ryanb’s awesome nested_form gem into my rails 3.1.3

  • 0

I’m having a rough go integrating ryanb’s awesome nested_form gem into my rails 3.1.3 application. I’m afraid my Javascript skills are too limited to know whether it’s my code (likely) or the gem that needs changed. Maybe someone here can help.

The setup: I have a “:households” class that :accepts_nested_attributes_for “:members (people)”. I’m running a development server. I moved nested_form.js to the /app/assets/javascripts directory. I’m almost positive it is only being sourced once.

The problem: if, in the households controller “new” method, I do this:

@household = Household.new

I see only the household-native fields in the view (expected), and the “link_to_remove” and “link_to_add” links render/delete a members-fields partial (expected). If, however, I do this:

@household = Household.new
@household.members.build

I see the household-native fields in the view (expected), one rendering of the member-native fields partial (expected), but the “link_to_remove” and “link_to_add” do nothing (unexpected). I cannot add another :members partial at that point, nor remove the already displayed :members partial.

I’m stumped. Below are stripped-down source files that seem relevant. I’m getting the nested_form plugin from the git repository (last bundled 2012.04.18)…


/app/models/household.rb

class Household < ActiveRecord::Base
  has_many :members, :class_name => "Person"
  accepts_nested_attributes_for :members
  attr_accessible :id, :name, :member_ids
  attr_accessible :members_attributes
end #class

/app/models/person.rb

class Person < ActiveRecord::Base
  belongs_to :household  
  attr_accessible :id, :name_given, :name_middle, :name_family, :household_id 
end #class

/app/controllers/households_controller.rb

  <snip>
  # GET /households/new
  # GET /households/new.json
  def new
    @household = Household.new
    @household.members.build     # <---- Removing this changes the behavior

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @household }
    end
  end

/app/views/households/new.html.haml

.headbg
  .pad
    %h2 Enter a New Household
= render 'form'

/app/views/households/_form.html.haml

= nested_form_for @household, :html => { :class => "form-horizontal"} do |f|

  %fieldset 
    %legend Household

    .control-group
      = f.label( :name, { :class => 'control-label'} )
      .controls
        = f.text_field( :name, { :class => 'span5', :placeholder => '[household name]'} )

  %fieldset 
    %legend Household Members
    = f.fields_for :members, :html => { :class => "form-inline"} do |nested_f|
      = render :partial => 'people/nested_person_form', :locals => { :f => nested_f }
      = yield :nested_person_form
    %p
      = f.link_to_add "New Household Member", :members 

  .form-actions
    = button_tag( :class => "btn btn-primary", :disable_with => "Saving..."  ) do
      %i.icon-ok.icon-white
      Save
    = link_to households_path do
      .btn.btn-info
        %i.icon-arrow-left.icon-white
        Back to Households

/app/views/people/_nested_person_form.html.haml

- content_for :nested_person_form do

  .nested-fields
    .row
      .span8 
        .control-group
          = f.label( "Name", { :class => 'control-label'} )
          .controls
            = f.text_field( :name_given, { :class => 'span2', :placeholder => '[first]'} )
            = f.text_field( :name_middle, { :class => 'span2', :placeholder => '[middle]'} )
            = f.text_field( :name_family, { :class => 'span2', :placeholder => '[last]'} ) 
      .span1
        = f.link_to_remove "Remove"

/app/assets/javascripts/nested_form/nested_form.js

jQuery(function($) {
  window.NestedFormEvents = function() {
    this.addFields = $.proxy(this.addFields, this);
    this.removeFields = $.proxy(this.removeFields, this);
  };

  NestedFormEvents.prototype = {
    addFields: function(e) {
      // Setup
      var link    = e.currentTarget;
      var assoc   = $(link).attr('data-association');            // Name of child
      var content = $('#' + assoc + '_fields_blueprint').html(); // Fields template

      // Make the context correct by replacing new_<parents> with the generated ID
      // of each of the parent objects
      var context = ($(link).closest('.fields').find('input:first').attr('name') || '').replace(new RegExp('\[[a-z]+\]$'), '');

      // context will be something like this for a brand new form:
      // project[tasks_attributes][new_1255929127459][assignments_attributes][new_1255929128105]
      // or for an edit form:
      // project[tasks_attributes][0][assignments_attributes][1]
      if (context) {
        var parentNames = context.match(/[a-z_]+_attributes/g) || [];
        var parentIds   = context.match(/(new_)?[0-9]+/g) || [];

        for(var i = 0; i < parentNames.length; i++) {
          if(parentIds[i]) {
            content = content.replace(
              new RegExp('(_' + parentNames[i] + ')_.+?_', 'g'),
              '$1_' + parentIds[i] + '_');

            content = content.replace(
              new RegExp('(\\[' + parentNames[i] + '\\])\\[.+?\\]', 'g'),
              '$1[' + parentIds[i] + ']');
          }
        }
      }

      // Make a unique ID for the new child
      var regexp  = new RegExp('new_' + assoc, 'g');
      var new_id  = new Date().getTime();
      content     = content.replace(regexp, "new_" + new_id);

      var field = this.insertFields(content, assoc, link);
      $(link).closest("form")
        .trigger({ type: 'nested:fieldAdded', field: field })
        .trigger({ type: 'nested:fieldAdded:' + assoc, field: field });
      return false;
    },
    insertFields: function(content, assoc, link) {
      return $(content).insertBefore(link);
    },
    removeFields: function(e) {
      var link = e.currentTarget;
      var hiddenField = $(link).prev('input[type=hidden]');
      hiddenField.val('1');
      // if (hiddenField) {
      //   $(link).v
      //   hiddenField.value = '1';
      // }
      var field = $(link).closest('.fields');
      field.hide();
      $(link).closest("form").trigger({ type: 'nested:fieldRemoved', field: field });
      return false;
    }
  };

  window.nestedFormEvents = new NestedFormEvents();
  $('form a.add_nested_fields').live('click', nestedFormEvents.addFields);
  $('form a.remove_nested_fields').live('click', nestedFormEvents.removeFields);
});

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T08:18:22+00:00Added an answer on June 11, 2026 at 8:18 am

    Make sure you have one of the latest jQuery.js files linked in your head. Once that is loaded do not use the nested_form.js file that installs from the gem. Instead use jquery_nested_form.js.

    Here is a solution that will work fine so long as you have jquery linking before the jquery_nested_form file:

    <%= javascript_include_tag :defaults, 'jquery_nested_form' %>
    

    Here is the code for the jquery_nested_form.js file:

        jQuery(function($) {
      window.NestedFormEvents = function() {
        this.addFields = $.proxy(this.addFields, this);
        this.removeFields = $.proxy(this.removeFields, this);
      };
    
      NestedFormEvents.prototype = {
        addFields: function(e) {
          // Setup
          var link    = e.currentTarget;
          var assoc   = $(link).attr('data-association');            // Name of child
          var content = $('#' + assoc + '_fields_blueprint').html(); // Fields template
    
          // Make the context correct by replacing new_<parents> with the generated ID
          // of each of the parent objects
          var context = ($(link).closest('.fields').closestChild('input, textarea').eq(0).attr('name') || '').replace(new RegExp('\[[a-z]+\]$'), '');
    
          // context will be something like this for a brand new form:
          // project[tasks_attributes][new_1255929127459][assignments_attributes][new_1255929128105]
          // or for an edit form:
          // project[tasks_attributes][0][assignments_attributes][1]
          if (context) {
            var parentNames = context.match(/[a-z_]+_attributes/g) || [];
            var parentIds   = context.match(/(new_)?[0-9]+/g) || [];
    
            for(var i = 0; i < parentNames.length; i++) {
              if(parentIds[i]) {
                content = content.replace(
                  new RegExp('(_' + parentNames[i] + ')_.+?_', 'g'),
                  '$1_' + parentIds[i] + '_');
    
                content = content.replace(
                  new RegExp('(\\[' + parentNames[i] + '\\])\\[.+?\\]', 'g'),
                  '$1[' + parentIds[i] + ']');
              }
            }
          }
    
          // Make a unique ID for the new child
          var regexp  = new RegExp('new_' + assoc, 'g');
          var new_id  = new Date().getTime();
          content     = content.replace(regexp, "new_" + new_id);
    
          var field = this.insertFields(content, assoc, link);
          // bubble up event upto document (through form)
          field
            .trigger({ type: 'nested:fieldAdded', field: field })
            .trigger({ type: 'nested:fieldAdded:' + assoc, field: field });
          return false;
        },
        insertFields: function(content, assoc, link) {
          return $(content).insertBefore(link);
        },
        removeFields: function(e) {
          var $link = $(e.currentTarget),
              assoc = $link.data('association'); // Name of child to be removed
          
          var hiddenField = $link.prev('input[type=hidden]');
          hiddenField.val('1');
          
          var field = $link.closest('.fields');
          field.hide();
          
          field
            .trigger({ type: 'nested:fieldRemoved', field: field })
            .trigger({ type: 'nested:fieldRemoved:' + assoc, field: field });
          return false;
        }
      };
    
      window.nestedFormEvents = new NestedFormEvents();
      $('form a.add_nested_fields').live('click', nestedFormEvents.addFields);
      $('form a.remove_nested_fields').live('click', nestedFormEvents.removeFields);
    });
    // http://plugins.jquery.com/project/closestChild
    /*
     * Copyright 2011, Tobias Lindig
     *
     * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
     * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
     *
     */
    (function($) {
            $.fn.closestChild = function(selector) {
                    // breadth first search for the first matched node
                    if (selector && selector != '') {
                            var queue = [];
                            queue.push(this);
                            while(queue.length > 0) {
                                    var node = queue.shift();
                                    var children = node.children();
                                    for(var i = 0; i < children.length; ++i) {
                                            var child = $(children[i]);
                                            if (child.is(selector)) {
                                                    return child; //well, we found one
                                            }
                                            queue.push(child);
                                    }
                            }
                    }
                    return $();//nothing found
            };
    })(jQuery);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
We're building an app, our first using Rails 3, and we're having to build
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am currently running into a problem where an element is coming back from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.