简体   繁体   中英

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM