Hassan Yousuf
Hassan Yousuf

Reputation: 731

Rails - Routing error when destroying session path in Devise

I created a simple rails app and implemented devise on it, I added the login/register feature and it works fine. But when I add the "log out" feature, it gives me a Routing Error that No route matches [GET] "/ideas/sign_out"

Here is what I implemented:

<% unless idea_signed_in? %>
    <li><a href="#">Explore</a></li>
    <li><%= link_to "Sign in", new_idea_session_path %></li>
    <li><%= link_to "Share an idea", new_idea_registration_path %></li>
<% else %>
    <li><a href="#">Dashboard</a></li>
    <li><a href="#">Explore</a></li>
    <li><%= link_to "Sign Out", destroy_idea_session_path, method: :delete %></li>
<% end %>

Even tried it with :method => :delete but still nothing. I ran rake routes and my routes are valid:

destroy_idea_session_path DELETE /ideas/sign_out(.:format) devise/sessions#destroy

I added <%= javascript_include_tag :defaults %> to my application.html.erb but still no luck.

My routes.rb

Rails.application.routes.draw do

  devise_for :ideas
  root 'welcome#index'

end

Upvotes: 1

Views: 653

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You know the problem already -

No route matches [GET] "/ideas/sign_out"

This means that you're trying to link to the logout link using the :get method.

The main cause of this is to forget to put the method: :delete switch in your link_to reference. To ensure this is not the problem, you can use the following:

<%= link_to "Logout", destroy_idea_session_path, method: :delete %>

JQuery

If your link is implemented like this, which it seems to be, the next potential issue is that you don't have jquery loaded in your views.

Rails delete method it doesn't work

The delete verb actually isn't supported by most browsers, and as such, Rails uses jquery to modify the HTML to pass the delete switch as part of the link's data attributes.

Nominally, you need to ensure that you have JQuery loaded in your views & layout:

#app/views/layouts/application.html.erb
<%= javascript_include_tag "application" %>

#app/assets/javascripts/application.js.erb
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

This will ensure JQuery is loaded, and your application can handle the DELETE method.

Upvotes: 2

Korey Enright
Korey Enright

Reputation: 104

Try changing devise_for :ideas to devise_for :ideas, sign_out_via [:delete]

It seems your controller is sending a get request instead of a delete request. Make sure you have Javascript enabled on whatever device you are using to test - the request falls back to GET if JS is not enabled.

EDIT: Make sure you find out what request your link is sending.

If all else fails, go to your Devise config file and change the line config.sign_out_via = :delete to config.sign_out_via = :get and remove , sign_out_via [:delete] from your routes file.

Upvotes: 2

Related Questions