简体   繁体   English

如何在Rails中的ruby中更新index.html.erb中的数据?

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

I create one app about product that has name , price and description . 我创建了一个有关产品的应用程序,该应用程序具有namepricedescription 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. index.html.erb中 ,我想向每个文本框添加文本框,然后单击“编辑”链接可以编辑,不需要进入/ 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. 如果要更新数据而不重新加载edit.html.erb文件,则需要使用AJAX。 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: 在您的js.erb文件中,您可以编写:

$("#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.
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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