0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】ルーティング【備忘録】

Last updated at Posted at 2022-10-15

下記のようにlogout_pathのような[ルート名]_pathのように記述し、routes.rbにルートを記述するとlogout.hrml.erbを呼び出すことができる。
ルート名の確認方法は下記のコマンドrails routesで確認できる。
ルート名は,as:'ルート名'でエイリアスを設定できるが、デフォルトでは[コントローラ名]_[アクション名]_pathのようになる。

$rails routes | grep 'home'
#ルート名        URL                       コントローラ名#アクション名
root GET             /                         home#top 
home_top GET         /home/top(.:format)       home#top
logout GET           /home/logout(.:format)    home#logout
routes.rb
Rails.application.routes.draw do
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  resources :todos
  devise_for :users
  root 'home#top'
  get 'home/top'
  get 'home/logout' => 'home#logout' # ,as:'logout' で logout_pathでも呼び出せる
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
home_controller.rb
class HomeController < ApplicationController
  def top; end

  def logout; end
end
aplication_controller.rb
class ApplicationController < ActionController::Base
  # 新規登録後のリダイレクト先をマイページへ
  def after_sign_in_path_for(_resource)
    if current_user
      flash[:notice] = 'ログインに成功しました'
      todos_path #  指定したいパスに変更
    end
  end

  def after_sign_out_path_for(_resource)
    flash[:notice] = 'ログアウトしました'
    logout_path
  end
end
logout.html.erb 
<h4 id="notice"><%= notice %></h4>
<% if user_signed_in? %>
ログインしています

<h4>メールアドレス: <%= current_user.email %></h4>
<%= link_to "ログアウト",destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to "トップへ",root_path,class:"btn btn-primary" %>
<% end %>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?