Eckenmeyer
Eckenmeyer

Reputation: 13

Rails destroy does not work and forwards to a wrong link

I am totally new to rails and struggle with the easiest stuff. I have the following problem:

When I try to destroy a search (from my model search) it does not work and I get redirected to "/search.48 (the search with id 48). It gives me the notice "We're sorry, but something went wrong." and in the console it says something with POST. Neither the search is deleted nor the redirect_to search_path is working. What am I doing wrong?

This is my controller:

def show
    @searches = current_user.searches
end

def destroy
    @search = Search.find(params[:id])
    @search.destroy
    flash[:success] = "Search deleted"
    redirect_to search_path
end

This is my view show:

<% @searches.each do |search| %> 
<%= search.title %>
<%= search.description %>
<%= button_to "delete", search, method: :destroy %>

My routes.rb:

get 'search' => 'searches#show'
resources :searches

And I also included <%= javascript_include_tag 'application' %> in the application.html.erb as well as //= require jquery and //= require jquery_ujs in the application.js file.

So I really can't find my mistake. Can someone help me?

Upvotes: 0

Views: 50

Answers (3)

Eckenmeyer
Eckenmeyer

Reputation: 13

I got it! In my router I wrote get 'search' => 'searches#show' and somehow my controller was confused with the search_path. Since I renamed it to get 'mysearches' => 'searches#show' and mysearches_path it works perfectly

Upvotes: 0

ruby_newbie
ruby_newbie

Reputation: 3285

have you tried:

  <%= button_to "Delete", { action: "delete", id: search.id },
                                    method: :delete %>

in you view. Also it appears you are redirecting to search_path but I am guessing you want searches_path.

Upvotes: 1

Fred Willmore
Fred Willmore

Reputation: 4624

In your view file, the code for the button should look like:

<%= button_to "delete", search, method: :delete %>

Note the method is :delete, not :destroy. It's a little confusing, because 'delete' is the REST verb, but 'destroy' is the controller action name.

Upvotes: 1

Related Questions