Search code examples
ruby-on-railserror-handlingrubygemsrails-routing

how to go to logout path in rails?


I am using rails 7 and When I click on logout it show an error that logout path is not found. Here is my code of routes.rb, session controller and header section for logout:

Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  root 'pages#home'
  get 'about', to: 'pages#about'
  resources :articles
  get "/signup", to: "users#new"
  resources :users, except: [:new]
  get "/login", to: "sessions#new"
  post "/login", to: "sessions#create"
  delete '/logout', to: 'sessions#destroy'

end




<li class="nav-item">
            <%= link_to "Log out", logout_path, method: :delete, class: "nav-link" %>
   </li>



 def destroy
    session[:user_id] = nil
    flash[:notice] = "Logged out"
    redirect_to root_path

  end

error message(please note that i have already added ujs)


Solution

  • Use button_to instead of link_to. This creates an actual form element instead of relying on JavaScript.

    <%= button_to "Log out", 
                  logout_path, 
                  method: :delete, 
                  class: "nav-link" %>
    

    For critical features like a log out that should "just work" this is recommended.

    If you for some reason actually need a link that sends non-GET requests then Turbo attaches it's event handler to data-turbo-method instead of data-method which was used by Rails UJS:

    <%= link_to "Log out", 
                 logout_path, 
                 data: { turbo_method: :delete }, 
                 class: "nav-link" %>
    

    The only real reason you would want this today is if your want to add a link inside of a form element that performs a non-GET request. This is because nested forms are not allowed in HTML.

    Note that in order for this to work Turbo has to be present on the page and working which can fail for many reasons depending on what asset pipeline you have in your application.