Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Cloning nested fields by JS/coffeescript

Javascript • Asked by Dmitry Amelchenko

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?

app/models/ticket.rb

Ticket has_many :items, dependent: :destroy

app/helpres/application_helper.rb

module ApplicationHelper
    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 |i|  
            render(association.to_s.singularize + "_fields", :f => i)  
    end  
        link_to name, "#", :onclick => h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
    end  
end

app/assets/javascripts/application.js

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

app/views/tickets/_form.html.erb

<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 %>  
</div>

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.