Fix issue with nested form in Rails 3.0.9 where remove_fields and add field link functionalities are not functioning properly

I've been watching Ryan Bates' nested_forms episodes 1 & 2 on RailsCasts, successfully implementing the functionality in one project without any issues. However, in a new project using the same reference, the remove and add field functionality is not working.

Here is my model:

has_many :contacts, :dependent => :destroy
accepts_nested_attributes_for :contacts, :reject_if => lambda { |a| a[:contact_name].blank? },     :allow_destroy => true

The form where I'm trying to use the add field link:


        <div class="TabbedPanelsContent">
            <%= f.fields_for :contacts do |builder| %>
            <%= render "contact_fields", :f => builder %>
            <% end %>
        <p><%= link_to_add_fields "Add Contact", f, :contacts %></p>

          </div>

The partial for contacts:

<div class="fields">
<p class="lable">Contact Name</p>
<p class="field"><%= f.text_field :contact_name %></p></br>

<p class="lable">Mobile Number</p>
<p class="field"><%= f.text_field :contact_mobile_number %></p></br>

<p class="lable">Email Address</p>
<p class="field"><%= f.text_field :contact_email %></p></br>
<p><%= link_to_remove_fields "remove", f %></p> </div>

In the Application helper, I created these methods:


# Method for removing fields
def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
  end

# Method for Adding fields

  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, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
  end

The application.js looks like this:


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

By using Firebug, I noticed an issue with the generated HTML:

<p><input type="hidden" value="false" name="customer[contacts_attributes][1][_destroy]"   id="customer_contacts_attributes_1__destroy"><a onclick="remove_fields(this); return false;" href="#">remove</a></p>

It seems that the value="false" might be causing the problem, as it should be value="1" according to my previous successful implementation. Can someone help me with this issue?

Answer №1

My struggles with deletion came to an end when I made the important addition of :allow_destroy => true in my main model.

Answer №2

Include the following JavaScript code in your application.js file

function hide_element(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide(); }

function show_element(link, category, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + category, "g"); $(link).parent().before(content.replace(regexp, new_id)); }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through an object using both dot and bracket notation

Can anyone shed some light on why I keep getting an 'undefined' message when trying to access object properties using dot notation like return contacts[i].prop;? However, if I use bracket notation like return contacts[i][prop];, it works fine an ...

Error: An error occurred because the program attempted to read properties of a null value, specifically the property "defaultPrevented"

There seems to be an issue with a script error involving both the bootstrap alert and my own close alert tag. I have a script set up to automatically close alerts after 2.5 seconds when certain user actions trigger them, such as creating a blog post or del ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Tips for adding a background image using React refs?

Seeking assistance with setting a background for a specific div using react ref, this is my attempted code snippet: The component class structure as follows: import React from 'react'; import PropTypes from 'prop-types'; import class ...

What is the best way to choose the right value based on parameters?

I am currently working on a solution using protractor where I have several options to consider. Specifically, I need to test timeslots between 1600 and 1900, along with an else statement. For instance, if the 1600 timeslot is selected, then the code shoul ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Synchronize JSON data with the Document Object Model (DOM

My current project is built using React, where I am rendering the page dynamically based on JSON data. The page consists of various component types, ranging from images to text content. Each component includes a delete option, allowing users to change im ...

Store the token securely in your browser's localStorage and set up interceptors

Struggling with saving the token in localStorage and pushing it in interceptors to send it with all requests. Currently, passing user data and token from Symfony controller to frontend, but facing roadblocks in saving the token in localStorage and settin ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...

The function $$.generatePoint is not recognized in the Billboard.js library

Having some trouble with integrating billboard.js into my Vue project as an alternative to using d3.js. Struggling to get it working in both my repository and a vanilla Vue project. Anyone familiar with the process of getting billboard.js running smoothly ...

Jquery: Undefined Key/Value Declaration

I'm diving into the world of associative arrays for the first time and trying to access data using keys. While my array is being constructed successfully, I'm struggling to actually retrieve the data. As a result, the console.log statement at the ...

Having trouble unselecting the previous item when selecting a new item in Reactjs

I have a list of items and I want to change the background color of the currently selected item only. The previously selected item should deselect. However, at the moment, all items are changing when I click on each one. Can anyone help me solve this issue ...

What is the process for deducting the ordered quantity from the available quantity once an order is confirmed

Although I'm not a fan of hard coding, I've been struggling to find a solution to my problem and some explanations are just not clicking for me. The issue at hand involves three data products in the cart, product details, and placed order data f ...

Having difficulty implementing interval to a maximum of 2 minutes or until a certain condition is fulfilled in Angular

In my current scenario, I am working with two APIs - apiOne and apiTwo. When I call apiOne, it should return a response. If the response is successful, then I need to pass this response as a parameter to apiTwo. ApiTwo will then provide another response wh ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

Expanding a list of object arrays through iteration: A step-by-step guide

// Initializing with one object let posi_val=[{top: '3px', left: '2px'}]; // Adding another object in the loop for (let i = 1; i < n; i++) { posi_val.push({ top: `${posi_val[i - 1].top.slice(0, -2) * 2}px`, l ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

When I apply properties in JavaScript, I find that I am unable to utilize the CSS "hover" feature

For a personal project I am currently working on, I decided to experiment with setting background colors using Javascript. However, I have encountered an issue where my CSS code that changes the hover property does not seem to work after implementing the J ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...