calyxofheld
calyxofheld

Reputation: 2128

why am i getting undefined method `destroy' for nil:NilClass?

I want to delete something posted by a user. But it's not working the way it normally does despite the fact that I'm mirroring a setup I've used in other apps.

My html:

 <div class="section-wrap">
    <% @colors.each do |color| %>
        <div class="swatch">
        <div class="colorblock" style="background-color: <%= color.backgroundcolor %>">
        </div>
        <h2>PANTONE<sup>2</sup></h2>
        <p><%= color.name %></p>
      </div>
          <div class="controls">
            <% if current_user %>
                <%= link_to 'Delete', @color, method: :delete %>
                <% end %>
            </div>
    <% end %>
</div>

My controller action:

def destroy
   @color.destroy
   redirect_to root_path
end

My routes.rb (in which I should not have to specify the delete route):

resources :colors
delete 'colors', to: 'colors#destroy'

And then rake routes gives the route I'd expect:

DELETE /colors/:id(.:format)        colors#destroy

But I get undefined method 'destroy' for nil:NilClass

Upvotes: 0

Views: 2909

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

2 issues:

#View
<% @colors.each do |color| %>
  <%= link_to 'Delete', color, method: :delete %> #-> @color doesn't exist
<% end %>

#Controller
def destroy
  @color = Color.find params[:id]
  @color.destroy
  redirect_to root_path
end

The above should work for you.

Upvotes: 1

Kristj&#225;n
Kristj&#225;n

Reputation: 18803

It doesn't look like you've loaded @color, and instance variables are automatically initialized to nil (in contrast with local variables, which raise an exception if you use them without assigning them). Hence, Ruby complains that destroy is undefined on nil. Load @color first:

@color = Color.find(params[:id])

If you're using Color.find_by_id somewhere else in your controller (eg. a before_action), perhaps the ID just doesn't correspond to an existing Color. Unlike find, find_by_id will return nil when the record is missing.

Upvotes: 5

Related Questions