LoginSignup
0
1

More than 1 year has passed since last update.

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

Posted at

ポートフォリオ作成したけど、なんか忘れてる・・
そうだ、ゲストユーザー機能!
ということで備忘録として簡単に実装方法を記載します。

前提

・ユーザー登録機能(devise)が実装されている

ルーティングの設定

guest_sign_inアクションはこのあとコントローラーで定義します。

config/routes.rb
post 'homes/guest_sign_in', to: 'homes#new_guest'

アクションの定義

以下にてguest_sign_inを定義します。

1.find_or_create_byでゲストユーザーがあれば取り出す、無ければ作成する にする
2. パスワードはセキュリティの関係でSecureRandom.urlsafe_base64のランダムで作成できるよう設定
3. railsが用意してるsign_inメソッドを利用して、先ほど定義したuserをログインさせる

controllers/homes_controller.rb
class HomesController < ApplicationController
  def new_guest
    user = User.find_or_create_by(email: 'guest@example.com') do |user|
        user.password = SecureRandom.urlsafe_base64 
    end
    sign_in user
    redirect_to root_path, notice: 'ゲストユーザーとしてログインしました。'
  end
end

リンクボタンの作成

あとはviewでボタンを作成すれば完成。

views/homes/index.html.haml
%p= link_to 'ゲストログイン(閲覧用)', homes_guest_sign_in_path, method: :post

参考資料

deviseの公式GitHub
Railsドキュメント(find_create_by)
簡単ログイン・ゲストログイン機能の実装方法(ポートフォリオ用)

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