简体   繁体   中英

How to update data in index.html.erb in ruby on rails?

I create one app about product that has name , price and description . In index.html.erb , I wanna add textbox to each of them and click edit link can edit don't need go to /products/id/edit.

How can I edit the product data?

    <% @products.each do |product| %>
      <tr>
        <form action="/products/<%= product.id %>" class="edit_person_<%= product.id %>" id="edit_person_<%= product.id %>" method="post">
          <input name="_method" type="hidden" value="patch" />
          <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
          <td><input id="product_name" name="product[name]" type="text" value="<%= product.name %>" /><br /></td>
          <td><input id="product_price" name="product[price]" type="text" value="<%= product.price %>" /><br /></td>
          <td><input id="product_descr" name="product[descr]" type="text" value="<%= product.descr %>" /><br /></td>
          <td><input name="commit<%= product.id %>" type="submit" value="edit" /></td>
        </form>
      </tr>
    <% end %>

You need to use AJAX if you want to update your data without reloading the edit.html.erb file. Below, I'm gonna show it how to this for one field, rest you can assume yourself.

<input id="product_price" name="product[price]" type="text" value="<%= product.price %>" />

In your js.erb file, you can write:

$("#product_price").focusout(function() {
    var productPrice = $(this).val();
    $.ajax({
        url: "/products/<%= product.id %>/edit",
        type: "POST",
        data: { product_price: productPrice}, // same way, other attributes
        success: function() {
            console.log("The result successfully came back from ther server.");
            // Now, here you can show a notice to the user that he has successfully update the record without reloading the page.
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM