ruby-on-rails - 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 传递给控制器?在线示例显示了我在做什么,但对我不起作用。
解决方案
您使用的是 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"]
推荐阅读
- sql - Oracle SQL 中四列 ROLLUP 的小计级别
- java - 单击取消按钮后JOptionPane如何退出代码
- enums - 特征可以用于枚举类型吗?
- java - 连接 AWS rds mysql 实例时获取 com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
- python - classinfo 类型列表
- amazon-web-services - 使用 AWS Cloudfront 和 S3 从 example.com 重定向到 www.example.com
- python - 从列表列表中复制浮点值
- perforce - 如何在 perforce 中列出当前用户和工作区?
- c++ - 为什么在模板函数中将两个 xtensor 表达式一起添加会错误广播?
- r - 如何在 r(ggmap,ggplot) 中修复地图上的名称和警告消息