未命名的方法`destroy'代表nil:NilClass

Nic*_*Res 9 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

每次用户提交一些统计信息时,我的应用程序都会成功为表创建行.现在我想提供一个删除按钮,以便能够删除一些行.

当我单击删除按钮时,我收到错误:

undefined method `destroy' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

看起来像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>
Run Code Online (Sandbox Code Playgroud)

"<%= render @status_updates%>"调用_status_update部分.

 <tr>
 .
 .
 .
 . 
 <% if current_user==(status_update.user) %> 
 <td>
       <%= link_to "delete", status_update, method: :delete %>

 </td>
 <%  end  %>         

</tr>                                    
Run Code Online (Sandbox Code Playgroud)

最后,这是StatusUpdateController

def destroy
    @status_update.destroy
    redirect_to root_url
end
Run Code Online (Sandbox Code Playgroud)

以下是错误页面上的参数:

{"_method"=>"delete",
 "authenticity_token"=>"w9eYIUEd2taghvzlo7p3uw0vdOZIVsZ1zYIBxgfBymw=",
 "id"=>"106"}
Run Code Online (Sandbox Code Playgroud)

Hun*_*der 11

由于您没有显示任何可以分配的代码(过滤器等)@status_update,我认为没有.所以,实例变量@status_update在你在你的destroy方法未设置.您需要使用对象的ID查询类.

重写你的destroy方法如下:

def destroy
    @status_update = StatusUpdate.find(params[:id])
    if @status_update.present?
      @status_update.destroy
    end
    redirect_to root_url
end
Run Code Online (Sandbox Code Playgroud)

注意:将classname替换为StatusUpdate您的实际类名.