No route matches [GET] “/logout” [rails]

2019-06-25 07:08发布

问题:

I get the following routing error when I click on "logout":

No route matches [GET] "/logout"

This is my application.html.erb file:

 <% if session[:user_id] %>
      <%= link_to 'Logout', logout_path, :method => :delete %>
    <% end %>

This is my routes.rb file:

get 'admin' => 'admin#index'
  controller :sessions do
    get 'login' => :new
    post 'login'=> :create
    delete 'logout' => :destroy
  end

  get "sessions/create"
  get "sessions/destroy"

Does anybody know how to solve this problem?

回答1:

Have you enabled the built-in JavaScript libraries that are required (jquery/jquery_ujs)? The delete method is not directly supported by browsers, so this ends up actually creating a form with a hidden field _method, that Rails interprets to direct you to the correct place.

Edit:

To enable these libraries, check your application layout file. This is usually located at app/views/layouts/application.html.erb, but this may vary if you've customised your app.

You'll need to have the following tags in the head section:

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

That should get this working for you, but if not, post back and I'll try to help further. It'd be useful if you could get your code online - on GitHub or somewhere else - so that we can all see what you're trying to do in context.



回答2:

change delete 'logout' => :destroy to get 'logout' => :destroy this will work.