0

I'm trying to add a delete action to my app, and I'm getting an odd error that I"m having trouble tracking down. It seems like the create action is being triggered even though I've assigned the button to the delete action. Based on the URL when I click on the delete button, it seems like it might be using GET, which I'm pretty sure isn't correct.

Any help is much appreciated!

Here's the error I'm getting when I click on a delete button in the index view.

class DogsController < ApplicationController
def create
    Dog.create(dog_params)

    @dogs = Dog.all
    redirect_to dogs_path
end

def new
    @dog = Dog.new
end

def edit
end

def delete
    @dog = Dog.find params[:id]
    @dog.destroy
    redirect_to dogs_path
end 

def show
    @dog = Dog.find params[:id]
end

def index
    @dogs = Dog.all
end

private

    def dog_params
        params.require(:dog).permit(:name, :breed)
    end
end

And here's the code for the index view:

<h1>List of Dogs</h1>

<table>
<thead>
    <tr>
        <td>Name</td>
        <td>Breed</td>
        <td>Details</td>
    </tr>
</thead>

<% @dogs.each do |d| %>
    <tr>
        <td><%= d.name %></td>
        <td><%= d.breed %></td>
        <td><%= d.id %></td>
        <td><%= link_to 'Details', dog_path(d.id) %></td>
        <td><%= link_to 'Edit', edit_dog_path(d.id) %></td>
        <td><%= button_to 'Delete', :method => :delete %></td>
    </tr>
<% end %>
</table>
1
  • Here's the example I was basing mine on; I didn't see a form associated with the delete action. Am I misinterpreting this? Thanks! Commented Jun 17, 2014 at 15:14

2 Answers 2

4

Rails will be looking for destroy not delete in your controller.

Change def delete to def destroy

Aha also noticed you're not specifying what you want to delete:

<%= button_to 'Delete', d, :method => :delete %>

Also in your create you're getting all Dogs then redirecting which is a waste, remove the @dogs = Dog.all query.

@dogs = Dog.all
redirect_to dogs_path
Sign up to request clarification or add additional context in comments.

4 Comments

Made the change, but still having the same issue. Thanks for the optimization tip as well.
What do you have in routes.rb and what do you see if you run rake routes?
Scratch that, updated answer. You've not set which object you want to delete.
That did it! I was wondering if I needed to pass an ID or something, seemed odd. The example used "post" instead of something like "p", which explains why it wasn't working when I was using "dog". Thanks for the help!
0

button_to must pass in a parameter like this

button_to 'Delete', dog, method: :delete

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.