每次用户提交一些统计信息时,我的应用程序都会成功地为表创建行。现在我想提供一个删除按钮来删除一些行。
当我单击删除按钮时,出现错误:
undefined method `destroy' for nil:NilClass
似乎 Rails 出于某种原因不理解这种情况下的 destroy 方法,或者 Rails 没有看到任何要销毁的东西,因此是 nil:NilClass。
我的第一个问题是确定是哪种情况(如果是其中一种)。
我的第二个问题是修复它:D
这是我的 show.html:
<% provide(:title, "Log" ) %>
<% provide(:heading, "Your Progress Log") %>
<div class="row">
<div class="span8">
<% if @user.status_update.any? %>
<h3>Status Updates (<%= @user.status_update.count %>)</h3>
<table>
<thead>
<tr>
<th>Entry Date</th>
<th>Weight</th>
<th>BF %</th>
<th>LBM</th>
<th>Fat</th>
<th>Weight Change</th>
<th>BF % Change</th>
<th>Fat Change</th>
</tr>
</thead>
<tbody class = "status updates">
<%= render @status_updates %>
</tbody>
<% end %>
</div>
</div>
“<%= render @status_updates %>”调用 _status_update 部分。
<tr>
.
.
.
.
<% if current_user==(status_update.user) %>
<td>
<%= link_to "delete", status_update, method: :delete %>
</td>
<% end %>
</tr>
最后,这是 StatusUpdateController
def destroy
@status_update.destroy
redirect_to root_url
end
以下是错误页面上的参数:
{"_method"=>"delete",
"authenticity_token"=>"w9eYIUEd2taghvzlo7p3uw0vdOZIVsZ1zYIBxgfBymw=",
"id"=>"106"}
最佳答案
由于您没有显示任何可以分配@status_update
的代码(过滤器等),所以我认为没有。因此,您的 destroy
方法中的实例变量 @status_update
未设置。您需要使用对象的 ID 查询该类。
重写你的销毁方法如下:
def destroy
@status_update = StatusUpdate.find(params[:id])
if @status_update.present?
@status_update.destroy
end
redirect_to root_url
end
注意:将类名 StatusUpdate
替换为您的实际类名。
关于ruby-on-rails - 未定义方法 `destroy' 对于 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275814/