LoginSignup
0
3

More than 1 year has passed since last update.

【Rails6】ゲストユーザー機能の実装例

Last updated at Posted at 2021-04-12

※2022年から技術系の記事は個人ブログに投稿しております。ぜひこちらもご覧ください→yamaday0u Blog

エンジニア転職でポートフォリオとなるアプリを開発する際、企業の方がアプリを確認しやすいようにユーザー登録しなくてもよいゲストユーザー機能の実装が望ましいという話をよく聞きます。

そこで今回は、ぼくが自分のポートフォリオで実装したゲストユーザー機能の例を紹介します。

前提

  • deviseを使ってユーザー登録機能が実装されている
  • Rails 6.0.3.5

動作確認

「ゲストユーザーとしてログインする」ボタンをクリックすると、ゲストユーザーでアプリにログインできます。
Image from Gyazo

ルーティングの設定

以下のようにパスとアクションを組み合わせを定義します
guest_log_inアクションはこのあとコントローラーで自作で定義するアクションです。

config/routes.rb
devise_scope :user do
  post 'users/guest_log_in', to: 'users/sessions#guest_log_in'
end

アクションの定義

以下のようにguest_log_inアクションを定義します。

app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  def guest_log_in
    user = User.guest
    sign_in user
    redirect_to calendars_path, notice: 'Logged in as a guest'
  end
end

アクションの中で使用しているsign_inメソッドは、deviseが提供する機能で、サインイン状態にします。

ちなみにdeviseの公式GitHubのdevise/app/controllers/devise/sessions_controller.rb内のDevise::SessionsController#createsign_inメソッドです。※調べたことを書いているのですが、もし間違っていたらご指摘ください。ソースコードはこちら

またguestメソッドはこのあとモデルで定義します。

モデルの定義

モデルにはクラスメソッドであるguestメソッドを定義します。

app/models/user.rb
class User < ApplicationRecord
  def self.guest
    find_or_create_by!(email: 'guest@guest.mail') do |user|
      user.name = 'ゲストユーザー'
      user.password = SecureRandom.urlsafe_base64
    end
  end
end

find_or_create_by!メソッドはRailsに用意されているメソッドで、「条件を指定して初めの1件を取得し、1件もなければ作成」します。

この場合、emailカラムがguest@guest.mailである初めのレコードを取得し、なければnameカラムが「ゲストユーザー」、passwordはランダムな値を生成してくれるRubyモジュールであるSecureRandomを使って生成し、新しいレコードを作成します。
ぼくのアプリではusersテーブルにnameカラムがあるため、nameの値を指定しています。

SecureRandomについては以下を参考にしてください。
Ruby 3.0.0 リファレンスマニュアル SecureRandomモジュール

リンクボタンの作成

リンクボタンは任意の場所に以下のように記述します。

<%= link_to "Log in as a guest", users_guest_log_in_path, method: :post %>

ゲストユーザーの編集ができないようにするアクション

ポートフォリオを公開した時にゲストユーザーを編集可能な状態していると、イタズラを受けてしまう危険性もあるので、編集できないようにするアクションを定義します。

app/controllers/users/registrations_controller.rb
before_action :ensure_normal_user, only: :edit

def ensure_normal_user
  if resource.email == 'guest@guest.mail'
    redirect_to user_path(@user.id), notice: 'You can not edit guest user'
  end
end

参考資料

0
3
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
3