Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `destroy' for nil:NilClass

My app successfully creates rows for a table every time a user submits some stats. Now I want to provide a delete button to be able to delete some rows.

When I click the delete button I get the error:

undefined method `destroy' for nil:NilClass

Seems like either rails doesn't understand the destroy method in this case for whatever reason, or rails doesn't see anything to destroy, hence the nil:NilClass.

My first question is in identifying which is the case, if either of those.

My second question is fixing it :D

Here's my 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>

The "<%= render @status_updates %>" calls the _status_update partial.

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

 </td>
 <%  end  %>         

</tr>                                    

And then finally, here is the StatusUpdateController

def destroy
    @status_update.destroy
    redirect_to root_url
end

Here are the parameters on the error page:

{"_method"=>"delete",
 "authenticity_token"=>"w9eYIUEd2taghvzlo7p3uw0vdOZIVsZ1zYIBxgfBymw=",
 "id"=>"106"}
like image 672
Nick Res Avatar asked Nov 07 '12 18:11

Nick Res


1 Answers

As you are not showing any code (filters or so) that could assign @status_update, I assume there is none. So, the instance variable @status_update in your in your destroy method is not set. You need to query the class with the object's ID.

Rewrite your destroy method as follows:

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

Note: Replace the classname StatusUpdate with your actual class name.

like image 65
HungryCoder Avatar answered Oct 18 '22 16:10

HungryCoder