首页 > 解决方案 > NoMethodError(nil:NilClass 的未定义方法“销毁”):

问题描述

我在删除我在 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 传递给控制器​​?在线示例显示了我在做什么,但对我不起作用。

标签: ruby-on-rails

解决方案


您使用的是 nil 的实例变量。destroy 方法应该使用类方法,例如,而不是

@client.destroy(params[:client_ids])

你可以试试

Client.destroy(params[:client_ids])

关于你的问题

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

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

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


推荐阅读