2

I'm new to rails and getting along with it okay so far and at the moment I'm trying to implement user authentication with Devise. Everything works except logging out. I've made the link to log out in my header like so:

<%= link_to 'Sign out', destroy_user_session_path, :method => :delete %>

And the file at app/config/initializers/devise.rb has the following set:

config.sign_out_via = :delete

To my knowledge since Devise uses a HTTP DELETE request to sign out, I need to specifically set the sign out link to DELETE. However, when clicking the link the request is still sent via GET, as I get this error:

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

From Google'ing it seems this is because I need the version of jQuery that got bundled with Rails to implement a kind of polyfill for the HTTP DELETE method. However, when I was cleaning up all my assets I opted to use the very latest version of jQuery and as such, this is in my application.js file:

//= require jquery-2.1.0
//= require bootstrap
//= require plupload.full.min

Even though jQuery is included, it's still sending the request over GET. Some people have suggested that I use <%= javascript_include_tag :defaults %> in my layout which I've tried, and that just 404's on defaults.js like so:

No route matches [GET] "/javascripts/defaults.js"

Is anyone able to explain a bit more about what's going on here and the necessary steps to resolve this issue? I'm aware I can just tell Devise to use GET to sign out but that's just avoiding the problem.

1 Answer 1

6

Non-GET requests from hyperlinks are not natively supported, so you need javascript code to do that. That's what jquery-ujs does (among other things), but you probably removed it when cleaning your assets.

You could include the jquery-ujs script, but according to the documentation it's not compatible with jQuery 2.0 or higher. So that's not an option if you want to keep using the latest jQuery version.

Other option is to use the button_to helper. It creates a form with a hidden input with the name _method and delete as value. It will use POST but rails is able to interpret the _method field and find the correct route, making Devise logout work.

<%= button_to 'Sign out', destroy_user_session_path, method: :delete %>

Hope it helps.

1
  • Thanks, solved my problem with the button_to method :) Jan 29, 2015 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.