Search code examples
ruby-on-railsdevise

Why does this link_to use GET rather than DELETE like I specified?


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

Solution

  • 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.