LoginSignup
maasiii
@maasiii

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

ログアウトできない。No route matches [GET] "/logout"

解決したいこと

ここに解決したい内容を記載してください。

①,ログアウトできるようにしたい。
②,ユーザーのログイン状況に応じて、ログイン、ログアウトbtnに変更させたい。

発生している問題・エラー

①に関しては、ログアウトを押すと ルーティングエラーになります。
②に関しては、ログインの状況に関わらず、ログアウトのみしか表示されません。(pathに/loginと入力すればlogin画面自体は表示されます。)

// ①エラー文 //
No route matches [GET] "/logout"

該当コードはそれぞれ以下になります。

routes.rb

Rails.application.routes.draw do
  root 'static_pages#home'
  get '/login', to: 'sessions#new'
  post '/login', to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'
  resources :users
end

sessions_controller.rb

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user&.authenticate(params[:session][:password])
      reset_session
      log_in user
      redirect_to user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new', status: :unprocessable_entity
    end
  end

  def destroy
    log_out
    redirect_to root_url, status: :see_other
  end
end

sessions_helper.rb

module SessionsHelper

  # 渡されたユーザーでログインする
  def log_in(user)
    session[:user_id] = user.id
  end

  # 現在ログイン中のユーザーを返す(いる場合)
  def current_user
    if session[:user_id]
      @current_user ||= User.find_by(id: session[:user_id])
    end
  end

  # ユーザーがログインしていればtrue、その他ならfalseを返す
  def logged_in?
    !current_user.nil?
  end

  def logged_in_user
    unless logged_in?
      flash[:danger] = "Please log in."
      redirect_to login_url
    end
  end

  # 現在のユーザーをログアウトする
  def log_out
    reset_session
    @current_user = nil   # 安全のため
  end
end

_header.html.erb

<header class="bg-primary fixed-top">
  <div class="container">
    <div class="row">
      <div class="d-flex justify-content-between mb-4">
        <%= link_to "My Portfolio", root_path, class: "home" %>
        <% if logged_in? %>
          <%= link_to "ログアウト", logout_path, data: { "turbo-method": :delete }, class: "btn btn-light header-btn" %>
        <% else %>
          <%= link_to "ログイン", login_path, class: "btn btn-light header-btn", role: "button" %>
        <% end %>
      </div>
    </div>
  </div>
</header>

ログアウト後のログ

Started GET "/logout" for 172.30.0.1 at 2023-05-08 12:34:13 +0000
Cannot render console from 172.30.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1

ActionController::RoutingError (No route matches [GET] "/logout"):

Started GET "/" for 172.30.0.1 at 2023-05-08 13:06:32 +0000
Cannot render console from 172.30.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by StaticPagesController#home as HTML
  Rendering layout layouts/application.html.erb
  Rendering static_pages/home.html.erb within layouts/application
  Rendered static_pages/home.html.erb within layouts/application (Duration: 0.7ms | Allocations: 7)
  User Load (5.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/helpers/sessions_helper.rb:11:in `current_user'
  Rendered layouts/_header.html.erb (Duration: 271.4ms | Allocations: 3767)
  Rendered layouts/_footer.html.erb (Duration: 0.0ms | Allocations: 8)
  Rendered layout layouts/application.html.erb (Duration: 387.8ms | Allocations: 8764)
Completed 200 OK in 402ms (Views: 394.0ms | ActiveRecord: 109.0ms | Allocations: 9032)

環境
ruby3.1.2
rails7
docker
bootstrap5.1

ruby on railsなどを参考にコーディングしています。

自分で試したこと

①に関しては、ルートパスが間違っていないか確認をしたり、コントローラーやヘルパーモジュールなども確認するも問題なさそうでした。様々な記事を見て'rails-ujs'が機能していないのではと思い、'application.js'を確認すると、

application.js
//= require rails-ujs

が記述なかったので、記述しました。思えば、環境構築時に'application.js'自体なかったのでそりゃそうか、という感じでした。。
これで解決!!と思ったら、何も変化なし、、、
chatGPTなども活用するも、行き詰まってしまったので質問させていただきました。
慣れないdockerでの環境構築で作ったので、環境的な問題があるのかもしれない、、、

②に関しても同様に、pathが間違っていないか?アクションの定義が間違っていないか?確認するも、わからず、ログイン自体上手くできないのが関係しているのでは?と思い一緒に投げさせていただきました。

初歩的な質問になりますが、ご教授の方をどうぞよろしくお願いいたします🙇

0

2Answer

Comments

  1. @maasiii

    Questioner

    @apierce
    参考記事の共有ありがとうございます!

    <%= link_to "ログアウト", logout_path, data: { "turbo-method": :delete }, class: "btn btn-light header-btn" %>
    

    ここの記述は問題ないと思っているのですが、必要なgemがインストールされていないということでしょうか?

    Gemfileは以下になります。

    source "https://rubygems.org"
    git_source(:github) { |repo| "https://github.com/#{repo}.git" }
    
    ruby "3.1.2"
    gem 'bootstrap', '~> 5.1'
    gem 'sass-rails', '>= 6'
    gem 'jquery-rails'
    
    # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
    gem "rails", "~> 7.0.4", ">= 7.0.4.3"
    
    # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
    gem "sprockets-rails"
    
    # Use postgresql as the database for Active Record
    gem "pg", "~> 1.1"
    
    # Use the Puma web server [https://github.com/puma/puma]
    gem "puma", "~> 5.0"
    
    # Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
    gem "importmap-rails"
    
    # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
    gem "turbo-rails"
    
    # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
    gem "stimulus-rails"
    
    # Build JSON APIs with ease [https://github.com/rails/jbuilder]
    gem "jbuilder"
    
    # Use Redis adapter to run Action Cable in production
    # gem "redis", "~> 4.0"
    
    # Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
    # gem "kredis"
    
    # Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
    gem "bcrypt", "~> 3.1.7"
    
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
    gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]
    
    # Reduces boot times through caching; required in config/boot.rb
    gem "bootsnap", require: false
    
    # Use Sass to process CSS
    # gem "sassc-rails"
    
    # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
    # gem "image_processing", "~> 1.2"
    
    group :development, :test do
      # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
      gem "debug", platforms: %i[ mri mingw x64_mingw ]
    end
    
    group :development do
      # Use console on exceptions pages [https://github.com/rails/web-console]
      gem "web-console"
    
      # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
      # gem "rack-mini-profiler"
    
      # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
      # gem "spring"
    end
    
    group :test do
      # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
      gem "capybara"
      gem "selenium-webdriver"
      gem "webdrivers"
    end
    
    

    お時間ある際にご教授いただけますと幸いです!🙇

  2. @maasiii

    rails-ujsTurboがごっちゃになってしまっていそうです!
    rails7からは標準でTurboが使われています

  3. @maasiii

    Questioner

    自己解決いたしました。

    結論

    上記記事を実施し、以下のコードを、、

    sessions_controller.rb
    def destroy
      log_out
      redirect_to root_url, status: :see_other
    end
    

    このように変更しました。

    sessions_controller.rb
    def destroy
      log_out
      redirect_to root_path, status: :see_other
    end
    

    ちなみに、手動で作成していた'application.js'は削除しました。
    やはり、環境構築がうまくできていなかったようです。。
    railsについてももっと知識が必要だと痛感しました。。公式を見るようにしていきます!!

    @apierce さんのおかげで環境に対する予測ができました。ありがとうございます!!

こちらの記事を参考にjqueryも記述とgem installしましたが解決しませんでした。。

0

Your answer might help someone💌