使用ajax和rails删除表记录时发现404错误

时间:2016-05-26 03:15:22

标签: ruby-on-rails ajax

我正在尝试使用rails ajax删除表行。但我在控制台中收到以下错误。

<%= link_to 'Destroy', spare, method: :delete, data: { confirm: "Are you sure you want to delete the #{spare.name}?" }, class: "btn btn-danger btn-xs",remote: true %></td> 

以下是我的代码块。

//$('tr #<%= @spare.id %>').slideUp();
var element = document.getElementById(<%= @spare.id %>);
alert(element);
alert(hello); 
element.parentNode.removeChild(element);

destroy.js.erb文件

<% @spares.each_with_index do |spare, index| %>
      <tr id="li_<%= spare.id %>">
        <td><%= index + 1 %></td>
        <td><%= spare.name %></td>

        <!-- authorization check -->
        <% if can? :show, Spare %>
          <td><%= link_to 'Show', spare, class: "btn btn-warning btn-xs" %> 
        <% end %>

        <!-- authorization check -->
        <% if can? :edit, Spare %>
          <%= link_to 'Edit', edit_spare_path(spare), class: "btn btn-primary btn-xs" %> 
         <% end %>

         <!-- authorization check -->
         <% if can? :destroy, Spare %>
           <%= link_to 'Destroy', spare, method: :delete, data: { confirm: "Are you sure you want to delete the #{spare.name}?" }, class: "btn btn-danger btn-xs",remote: true %></td>

**上述代码中的提示也未显示。 **

以下是我的表格:

 "/spares" for 127.0.0.1 at 2016-05-26 09:02:29 +0530
  ActionController::RoutingError (No route matches [DELETE] "/spares"):

我检查了在rails面板中呈现的格式,它显示了js。但渲染并不显示destroy.js.erb。

以下是服务器日志中的错误

{{1}}

1 个答案:

答案 0 :(得分:0)

请这样做。

index.html.erb

    <% @spares.each_with_index do |spare, index| %>
      <tr id="li_<%= spare.id %>">
        <td><%= index + 1 %></td>
        <td><%= spare.name %></td>

      <!-- authorization check -->
      <% if can? :show, Spare %>
       <td><%= link_to 'Show', spare, class: "btn btn-warning btn-xs" %></td>
      <% end %>

      <!-- authorization check -->
      <% if can? :edit, Spare %>
       <td><%= link_to 'Edit', edit_spare_path(spare), class: "btn btn-primary btn-xs" %> </td>
      <% end %>

      <!-- authorization check -->
      <% if can? :destroy, Spare %>

        <td><%= link_to 'Destroy', spare, method: :delete, data: { confirm: "Are you sure you want to delete the #{spare.name}?" }, class: "btn btn-danger btn-xs",remote: true %></td>
      <% end %>
      </tr>  
    <% end %>

spares_controller.rb

  def destroy
    @spare.destroy
    respond_to do |format|
      format.html { redirect_to spares_url, notice: 'Spare was successfully destroyed.' }
      format.js
    end
  end

destroy.js.erb

$("#li_<%= @spare.id %>").remove()

在销毁操作之前,确保在控制器中进行过滤之前有set_spare。 像这样。

def set_spare
  @spare = Spare.find(params[:id])
end