LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】Devise ゲストユーザーログイン機能

Posted at

ポートフォリオにゲストユーザーログイン機能を下記の記事で無事に実装できました。
本当に詳しく書かれていて本当に助かります。。。
この記事では、復習を兼ねて少し解説していきます。

ルーティング

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

devise_fordevice_scopeの違いは?

devise_forについて

Includes devise_for method for routes. This method is responsible to generate all needed routes for devise, based on what modules you have defined in your model.

devise_scopeについて

You can pass a block to devise_for that will add any routes defined in the block to Devise's list of known actions. This is important if you add a custom action to a controller that overrides an out of the box Devise controller.

引用元

devise_forは、モデル(今回はUser)がログイン、新規登録などに必要なルーティングを生成し、
devise_scopeは、deviseに新規アクションを追加した際にルーティングを設定するために使用します。

コントローラー

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

sign_in とは?

sign_in はdeviseのメソッドです。
すでに登録済みユーザーのログインをするメソッドになります。

Sign in a user that already was authenticated. This helper is useful for logging users in after sign up. All options given to sign_in is passed forward to the set_user method in warden. If you are using a custom warden strategy and the timeoutable module, you have to set env = true in the request to use this method, like we do in the sessions controller:
引用元

モデル

app/models/user.rb
def self.guest
  find_or_create_by!(email: 'guest@example.com') do |user|
    user.password = SecureRandom.urlsafe_base64
    user.name = "Guest"
  end
end

find_or_creat_by! メソッドとは?

ユーザーが存在すれば、ユーザーを取得し、なければ作成します。
なので、仮にゲストユーザーが削除されても新規で作成されるのでログインは可能ということですね。

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