Koin Arab
Koin Arab

Reputation: 1107

No route matches [GET] "/logout" [rails]

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?

Upvotes: 9

Views: 7408

Answers (4)

Rasheed Starlet
Rasheed Starlet

Reputation: 11

It is 2023 and I had the same problem. I am with rails 7.0.8 my code is delete "/logout", to: "sessions#destroy"

I had to change it to get "/logout", to: "sessions#destroy"

and it works. I honestly have no idea why it works but it does. Makes no sense to me why we have to send a get request instead.

Upvotes: 1

Vitalii Shevchenko
Vitalii Shevchenko

Reputation: 1

For the version RoR 7.0.4 and higher

  1. Add to the app/assets/javascript/application.js

    //= require rails-ujs
    
  2. In the file app/views/layouts/application.html.erb put the rows to into comment such or delete it

    <!--%= stylesheet_link_tag "application", "data-turbo-track": "reload" %-->
    <!--%= javascript_importmap_tags %-->
    
  3. Add the new rows here

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

And all will be work. Have a nice day)

Upvotes: 0

Steve Hill
Steve Hill

Reputation: 2321

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.

Upvotes: 9

jimagic
jimagic

Reputation: 4065

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

Upvotes: 11

Related Questions