NoMethodError(nil:NilClass的未定义方法“ destroy”):

时间:2019-09-03 01:41:35

标签: ruby-on-rails

我在删除在Rails中创建的客户端时遇到问题。我正在使用Rails 6.0

“ nil:NilClass的未定义方法`destroy'”

控制器:

    class ClientsController < ApplicationController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

 def destroy_multiple
@client.destroy(params[:client_ids])
respond_to do |format|
  format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' }
  format.json { head :no_content }
 end
end

查看:

<div class="container">
  <div class="table-responsive">
    <%= form_tag destroy_multiple_clients_path, method: :delete do %>

<table class="table table-hover">
  <thead>
    <tr class="table-secondary">
      <th scope="col" ><input type="checkbox"></th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone number</th>
      <th>Client Type</th>
      <th>Nickname</th>
    </tr>
  </thead>

  <tbody>
    <% @clients.each do |client| %>
      <tr>
        <td><%= check_box_tag "client_ids[]", client.id %></td>
        <td><%= link_to client.name, client, :class => "clientname" %></td>
        <td><%= client.email %></td>
        <td><%= client.phone_number %></td>
        <td><%= client.client_type %></td>
        <td><%= client.nickname %></td>
    <% end %>
  </tbody>
</table>
</div>

 <hr class="featurette-divider">
   <%= submit_tag "Delete selected", :class => 'btn btn-primary btn-xs' %>
   

控制台:

 Parameters: {"authenticity_token"=>".................==", "client_ids"=>["11"], "commit"=>"Delete selected"}
Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.0ms | Allocations: 1019)



NoMethodError (undefined method `destroy' for nil:NilClass):

app/controllers/clients_controller.rb:65:in `destroy_multiple'

不确定我在这里想念什么吗?如何将控制台中显示的ID传递给控制器​​?在线示例显示了我在做什么,但对我不起作用。

1 个答案:

答案 0 :(得分:1)

您使用的实例变量为nil。 destroy方法应使用class方法 例如 代替

@client.destroy(params[:client_ids])

您可以尝试

Client.destroy(params[:client_ids])

关于您的问题

  

如何将控制台中显示的ID传递给控制器​​?   正如您在堆栈跟踪中所证明的那样,您已经在这样做了

Parameters: {"authenticity_token"=>".................==", "client_ids"=>["11"], "commit"=>"Delete selected"}

您可以清楚地看到client_ids参数正在传递数组,因此方括号[]包含一个值为11的单个元素,因此=>["11"]