All threads / Cloning nested fields by JS/coffeescript
Ask A Question


You’re not receiving notifications from this thread.

Cloning nested fields by JS/coffeescript

Dmitrii Amelchenko asked in Javascript

SImple app has a two models and does the function to add nested model fields dynamically through JavaScript. But this stuff does not working with the Turbolinks 5. How to refactoring this code by JS/coffeescript, classes and data-behavior?


Ticket has_many :items, dependent: :destroy


module ApplicationHelper
    def link_to_add_fields(name, f, association)  
        new_object = f.object.class.reflect_on_association(association)  
        fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |i|  
            render(association.to_s.singularize + "_fields", :f => i)  
        link_to name, "#", :onclick => h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")


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


<h4 class="page-header">Items</h4>
<%= f.fields_for :items do |i| %>
    <%= render 'item_fields', f: i %>
<% end %>
<div class="form-group">
    <%= link_to_add_fields 'Add Item', f, :items %>  
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 70,078+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.