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 3 years have passed since last update.

【Rails】ゲストログイン用のユーザー作成〜ポートフォリオに最適〜

Last updated at Posted at 2021-02-21

アプリケーションにテストログイン機能をつけた話し

まだまだやりたいことはいっぱいあるけれど、AWSへのデプロイが終わったので見てもらうことを考えてゲストユーザーでのログイン機能をつけることにしました。

諸先輩方のアプリケーションを見てもついていない人はいないぐらい実装率が高いので今や当たり前の機能になっていると感じます。
そもそもログインして見てもらうのにわざわざ登録させるのも気が引けるし、せっかく時間を割いて見にきてくれるのだから、おもてなしの心があるべきだと思います。

ではdevise導入済みで話しを進めていきます。

1・app/controllers配下にusersがない場合

まずはコントローラーに新しいファイルを作成。

$rails g devise:controllers users

⬇️できたファイル

app
 ┣controllers
      ┣users
         ┗confirmations_controller.rb
         ┗passwords_controller.rb
         ┗registrations_controller.rb
         ┗sessions_controller.rb

users直下に4つのファイルができました。

2・routes.rbに記述

routes.rb
# devise_for :usersの部分に追加
Rails.application.routes.draw do
  devise_for :users, controllers: {
    registrations: 'users/registrations',
    sessions: 'users/sessions'
  }



# resources :users, only: [:show] がある場合はその下に記述
devise_scope :user do
 post 'users/guest_sign_in', to: 'users/sessions#new_guest'
end

3・sessions_controller.rbにてメソッドを定義

sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  def new_guest
    user = User.guest
    sign_in user
    redirect_to root_path, notice: "ゲストユーザーとしてログインしました。"
  end
end

フラッシュメッセージはお好みで。

4・userモデルにメソッドを定義

user.rb

# モデルに定義なのでselfからスタート

def self.guest
  find_or_create_by!(email: 'test@test.com') do |user|
    user.password = SecureRandom.alphanumeric(10) + [*'a'..'z'].sample(1).join + [*'0'..'9'].sample(1).join
    user.nickname = 'ゲストユーザー'
    user.gender_id = '4'   ⬅️ActiveHashの入力
    user.genre_id = '9'    ⬅️ActiveHashの入力
  end
end

ActiveHashを利用している場合はuser.gender_id = '4'などの記述で問題ありませんでした。
ゲストログインも通常のユーザー登録をする流れと同じ流れを辿るので、バリデーションがかけられていると未入力項目に対してエラーが出てしまう。
ここでしっかりと項目をうめておく。
passwordは最初SecureRandom.urlsafe_base64としていましたがAWSへのデプロイ時にエラーになり、ログを見るとバリデーションが不正とのこと。
記述を変えたら本番環境でも成功しましたので、もし引っかかってしまったら試してみて下さい。

5・ビューファイルを変更

new.html.erb
<%= link_to 'ゲストログインはこちら', users_guest_sign_in_path, method: :post %>

ボタンを作る場所などレイアウトに合わせて適用。

参考にさせて頂きました

@take18k_tech
簡単ログイン・ゲストログイン機能の実装方法(ポートフォリオ用)

@rie1224
Railsでテストアカウントでの簡単ログインの実装方法

ありがとうございました。

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?