LoginSignup
0
0

ゲストログイン機能について

Posted at

はじめに

ポートフォリオにゲストログインを実装したので
忘備録として残します。

その1.ルーティング

routes.rbにゲストログイン用のアクションを設定します。
SessionsControllerに新しいアクションguest_sign_inを準備します。

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

その2.コントローラ

guest_sign_inアクションを設定するため,app/controllersにusersディレクトリを作成し,その中に次のsessions_controller.rbを作成します。

app/controllers/users/sessions_controller.rb
# ゲストログイン機能
  def guest_sign_in
    user = User.guest
    sign_in user
    redirect_to parent_path(current_user.id)
  end

その3.モデル

find_or_create_by!で'guest@example.com' であるユーザーを検索します。
もし見つかればそのユーザーを返すが、無ければ作成します。
SecureRandom.alphanumeric(8)を使って、8文字のランダムな
英数字のパスワードを作成しています。

app/models/user.rb
# ゲストログイン機能
   def self.guest
     find_or_create_by!(email: 'guest@example.com') do |user|
      # 8文字の英数字のランダムパスワードを指定
       user.password = SecureRandom.alphanumeric(8)
       user.name = "guest_user"
     end
   end

その4.ビュー

今回はtopページにログインボタンを実装するので以下を追加して下さい!

app/views/homes/top.html.erb
<%= link_to 'ゲストログイン(閲覧用)', users_guest_sign_in_path, method: :post%>
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