0

I am using devise, and this is my link:

<%= link_to "Logout", logout_path, method: :delete, class: "dropdown-item" %>

This is the output of the logs when I click the link:

Started GET "/logout" for ::1 at 2020-04-16 21:24:58 -0500
ActionController::RoutingError (No route matches [GET] "/logout"):

This is the HTML it generates:

<a class="dropdown-item" rel="nofollow" data-method="delete" href="/logout">Logout</a>

This is the relevant section of my routes.rb:

  devise_scope :user do
    delete "logout", to: "devise/sessions#destroy"
  end
Roman Alekseiev
  • 1,854
  • 16
  • 24
marcamillion
  • 32,933
  • 55
  • 189
  • 380
  • any javascript errors in console? Did you try this: https://stackoverflow.com/a/22004078/4414956 ? – nuaky Apr 17 '20 at 06:55
  • https://stackoverflow.com/questions/7465919/rails-link-to-method-geting-when-it-should-delete – Nithin Apr 17 '20 at 10:23
  • Does this answer your question? [Rails' link\_to method: GETing when it should DELETE](https://stackoverflow.com/questions/7465919/rails-link-to-method-geting-when-it-should-delete) – Eyeslandic Apr 17 '20 at 10:45
  • 2
    The reason its being sent as a GET request is that something is preventing the event listener declared by Rails UJS from working. This could be that your application.js is missing `require("@rails/ujs").start()` or a script error. Without that event listener its just a plain old link and browsers handle clicks on links by sending a GET request. For something as critical as a log out button I would consider hardening your app by using `button_to` instead which works even if javascript is turned off completely. – max Apr 17 '20 at 11:29
  • @max sorry for the delayed reply, but your suggestion about using `button_to` worked like a charm. The other links weren't very helpful but that `button_to` suggestion was perfect. Thanks! If you add it as an answer I will accept it. – marcamillion Apr 25 '20 at 08:03
  • Could be written as well as `require("rails-ujs").start()` depending on how you import it, I guess – Robert Jun 12 '21 at 15:55

1 Answers1

0

Per @max's comment on my question above:

The reason its being sent as a GET request is that something is preventing the event listener declared by Rails UJS from working. This could be that your application.js is missing require("@rails/ujs").start() or a script error. Without that event listener its just a plain old link and browsers handle clicks on links by sending a GET request. For something as critical as a log out button I would consider hardening your app by using button_to instead which works even if javascript is turned off completely.

So I changed the link_to to button_to and that worked like a charm.

marcamillion
  • 32,933
  • 55
  • 189
  • 380