LoginSignup
6
10

More than 3 years have passed since last update.

[Rails]ゲストログイン機能

Posted at

はじめに

ポートフォリオにゲストログイン機能があった方が良いとのことだったので実装してみました。

目次

  • 1. ルーティング
  • 2. コントローラー
  • 3. モデル
  • 4. ビュー

1. ルーティング

routes.rbにゲストログイン用のアクションを設定します。
deviseのsessionsコントローラーに新しくメソッドを追加しています。

config/routes.rb
Rails.application.routes.draw do
  devise_for :users
  devise_scope :user do
    post 'users/guest_sign_in', to: 'users/sessions#new_guest'
  end
  ~~
end

2. コントローラー

controllersの中にusersフォルダを作成しsessions_controller.rbファイルを作成。
new_guestメソッドをコントローラーに作成します。
guestメソッドはモデルに作成します。

app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  def new_guest
    user = User.guest
    sign_in user   # ユーザーをログインさせる
    redirect_to root_path, notice: 'ゲストユーザーとしてログインしました。'
  end
end

3. モデル

find_or_create_by!でゲストユーザーが無ければ作成、あれば取り出します。
あとはゲストユーザーがない時に作成するユーザー情報を記述しています。

app/models/user.rb
def self.guest
  find_or_create_by!(email: 'aaa@aaa.com') do |user|
    user.password = SecureRandom.urlsafe_base64
    user.password_confirmation = user.password
    user.nickname = 'サンプル'
    user.birthday = '2000-01-01'
  end
  ~~
end

4. ビュー

今回はヘッダーにゲストログイン用のボタンを作成しました。

app/views/shared/_header.html.erb
<ul class='lists-right'>
  <% if user_signed_in? %>
    <li><%= link_to current_user.nickname, user_path(current_user.id), class: "user-nickname" %></li>
    <li><%= link_to 'ログアウト', destroy_user_session_path, method: :delete, class: "logout" %></li>
  <% else %>
    <li><%= link_to 'ゲストログイン(閲覧用)', users_guest_sign_in_path, method: :post, class: "login" %></li>
    <li><%= link_to 'ログイン', new_user_session_path, class: "login" %></li>
    <li><%= link_to '新規登録', new_user_registration_path, class: "sign-up" %></li>
  <% end %>
</ul>

参考リンク

6
10
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
6
10