Ask A Question

Notifications

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?

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>
Reply
Join the discussion
Create an account Log in

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

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

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