Home > OS >  Why do I get Rails 7 Routing Error although route is defined?
Why do I get Rails 7 Routing Error although route is defined?

Time:09-14

I'm following the Rails Tutorial by Michael Hartl to build a tiny demo app. I'm stuck at the logout. This is my routes.rb:

Rails.application.routes.draw do
  resources :users

  get    "/login",   to: "sessions#new"
  post   "/login",   to: "sessions#create"
  delete "/logout",  to: "sessions#destroy"

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

  # Defines the root path route ("/")
  root 'users#index'
end

This is the relevant controller action:


  def destroy
    log_out
    redirect_to root_url, status: :see_other
  end

This is the session helper defining log_out:

  def log_out
    reset_session
    @current_user = nil
  end

and this is the link tag in the view:

      <%= link_to "Log out", logout_path, data: { 'turbo-method': :delete } %></span>

Screenshot of error

When I click on the logout link, I get this error. Expected behaviour: Log user out, redirect to login screen.

What am I doing wrong?

I don't know whether it's because of Turbo, or whether Turbo is even correctly installed. I've added gem 'turbo-rails' to the Gemfile and ran bundle afterwards without any effect.

CodePudding user response:

For me, adding the method: :delete worked along with data-turbo.

<span>
<%= link_to "Log out", destroy_user_session_path,method: :delete, data: { 'turbo-method': :delete } %></span>

CodePudding user response:

Check with passing method

<%= link_to "Log out", logout_path, method: :delete, data: { 'turbo-method': :delete } %>

or

<%= link_to "Log out", logout_path, method: :delete %>

CodePudding user response:

You were accessing the DELETE method route via GET. Have you run

rails turbo:install

You may want to change the sign out via GET instead of Delete in config/devise.rb

  # The default HTTP method used to sign out a resource. Default is :delete.

  config.sign_out_via = :get # <= change this from :delete to :get and remove the `method:` in your `link_to` helper

Here's the references: https://github.com/hotwired/turbo-rails https://github.com/heartcombo/devise/issues/5439

  • Related