使用ajax无法正常运行的Form_for更新操作

问题描述 投票:0回答:1

我正在通过创建一个简单的应用程序来管理产品作为数据表,从而学习ajax。在更新之前,任何事情(新的,创造的,编辑的)都做得很好。更新表单中的提交按钮在我单击时不执行任何操作。这是我的终端日志

Started GET "/products/3/edit" for ::1 at 2019-05-01 01:14:47 +0700
Processing by ProductsController#edit as JS
  Parameters: {"id"=>"3"}
  Product Load (0.4ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
  ↳ app/controllers/products_controller.rb:68
  Rendering products/edit.js.erb
  Rendered products/_editform.html.erb (1.8ms)
  Rendered products/edit.js.erb (14.1ms)
Completed 200 OK in 54ms (Views: 31.9ms | ActiveRecord: 0.4ms)

products_controller.rb

def update
respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { render :show, status: :ok, location: @product }        
        format.js
else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end

_product.html.erb

<tr>    
    <td colspan="3"> <%= product.id %></td>
    <td colspan="3"> <%= product.name %></td>
    <td><%= link_to 'Show', product %></td>
    <td><%= link_to 'Edit', edit_product_path(product), remote:true, class:'edit-btn' %></td>
    <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>

_editform.html.erb

<%= form_for @product do |f| %>
<tr>            
    <td colspan="3"><%= product.id %></td>
    <td colspan="3"><%= f.text_field :name %></td>
    <td><%= f.submit "Save", class: 'save-btn' %></td>
    <td></td>
    <td></td>
</tr>
<% end %>

edit.js.erb

$('.edit-btn').bind('ajax:success', function() {
   $(this).closest('tr').html('<%= j render 'editform', product: @product %>');
});

update.js.erb

    $('.save-btn').bind('ajax:success', function() {

       $(this).closest('tr').html('<%= j render 'product', product: @product %>');

});

我认为update.js.erb有问题。因为当我在顶部添加console.log('hello');时更新和编辑,但只编辑工作。而network只是展示edit -> status 200。谢谢你的帮助

ruby-on-rails ruby-on-rails-5
1个回答
0
投票

更新:我发现了错误。在我的_editform.html.erb中,在<tr>内部的Rails形式不会完全呈现html。 </form>不要包裹text_fieldsubmit按钮。这就是为什么提交按钮不做任何事情。

© www.soinside.com 2019 - 2024. All rights reserved.