goal
I have a page with a list of items coming from the Rails backend. I want to be able to edit a line in this list using Ajax calls through Rails UJS.
An approach
I added an edit button to the end of each line. The edit button is link_to ... :remote => true . Clicking on it again loads the list, but with the selected line in edit mode. An editable line is embedded in form ... :remote => true . The save button on this line is the submit button.
index.html.haml
#editor %table - @items.each do |item| %tr = render :partial => 'row', :locals => { :item => item }
_row.html.haml
... %td // a number of columns with attributes ... %td = link_to t("actions.edit"), edit_item_path(item), :remote => true = link_to t("actions.delete"), item_path(item), :remote => true, :method => :delete, :data => { :confirm => "Are you sure?" }
edit.html.haml
#editor %table - @items.each do |item| %tr - if item == @item = form_for @item, :url => item_path(@item), :remote => true, do |f| = render :partial => "row_form", :locals => { :f => f } - else = render :partial => 'row', :locals => { :item => item }
_row_form.html.haml
... %td // a number of columns with editable attributes ... %td %button{ :type => "submit" }=t("actions.save") = link_to t("actions.cancel"), items_path, :remote => true
Ajax response handling
$("#editor").on("ajax:success", function(event, data, status, xhr) { $("#editor").html($(data).find("#editor").html()); });
Problem
When I load the list page in edit mode /items/12/edit , the line item 12 is editable. Pressing the save button presents the form via Ajax correctly and loads the /items index partial, replacing the editable list with jQuery. Pressing the button, click the edit button again, reload the edit page (for example, /items/12/edit ), the inline form. Only this time, the form is no longer submitted when the save button is pressed. It seems that the submit event handler is not tied to a dynamically loaded remote form.
Question
How can I submit a remote form downloaded via Ajax, preferably using the Rails UJS approach?
Duplicates
I know that there are duplicates of this question, but none of them answered. Hope someone finally comes to a definite answer.