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

时间:2015-06-09 06:43:47

标签: ruby-on-rails ruby

我创建了一个关于包含namepricedescription的产品的应用。在 index.html.erb 中,我想为每个文件添加文本框,然后点击编辑链接即可编辑,不需要转到/ products / id / edit。

如何编辑产品数据?

    <% @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 %>

1 个答案:

答案 0 :(得分:-1)

如果您想更新数据而不重新加载 edit.html.erb 文件,则需要使用AJAX。下面,我要告诉它如何为一个领域,休息你可以假设自己。

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

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