0
1

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.

簡単ログイン機能実装

Last updated at Posted at 2020-08-19

自分用にまとめます。
新規登録なしでポートフォリオを見てもらえるように実装。
user、admin両方作成

guest userの作成

models/user.rb

  def self.guest
    # 以下の情報を持ったユーザーを探す、または作成する
    find_or_create_by!(email: 'test@example.com', name: 'guest') do |user|
      user.password = SecureRandom.urlsafe_base64
    end
  end
registrations_controller.rb

  def check_guest
    # 以下のメールアドレスのユーザーが変更や削除を行おうとした時はマイページに飛ばす
    if resource.email == 'guest@example.com'
      redirect_to user_path(user), alert: 'ゲストユーザーの変更・削除はできません。'
    end
  end
users_controller.rb
  # ユーザー情報の編集や削除はできないようにusers_controllerに追記
  before_action :check_guest, only: [:update, :destroy]
sessions_controller.rb
  # ログイン処理
  def new_guest
    user = User.guest
    sign_in user
    redirect_to user_path(user), notice: 'ゲストユーザーとしてログインしました。'
  end
config/routes.rb

  devise_for :users, controllers: {
    sessions:      'users/sessions',
    passwords:     'users/passwords',
    registrations: 'users/registrations'
  }

  devise_scope :user do
    post 'users/guest_sign_in', to: 'users/sessions#new_guest'
  end
application.html.slim
  li.btn.btn-light.home-btn= link_to users_guest_sign_in_path, method: :post, class: 'list' do
    i.fas.fa-key
    |  user guest

※adminも全く同じような考え方で記述していけば実装可

完成!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?