I think that the guest login function is almost indispensable when creating a portfolio of web applications.
There are several articles on the guest login function on Qiita, but currently (December 2020) most of them use devise. I implemented the login function without using devise, so I had a little trouble. If you are creating a portfolio without using devise like me, please refer to it!
Note In this article, I won't go into details on how to implement the login feature. If you want to know about the login function that does not use devise, please refer to the following article.
https://qiita.com/d0ne1s/items/7c4d2be3f53e34a9dec7
** ① Create controller **
python
$ rails g controller guest_sessions_controller
** ② Add route ** The guest user is not deleted, so there is no destroy action.
routes.rb
post 'guest_login', to: "guest_sessions#create"
** ③ create action creation ** The password can be anything, but this time I set it randomly.
guest_sessions_controller.rb
class GuestSessionsController < ApplicationController
def create
user = User.find_or_create_by(email: "[email protected]") do |user|
user.password = SecureRandom.urlsafe_base64
user.name = "Guest user"
end
session[:user_id] = user.id
flash[:success] = "You logged in as a guest user"
redirect_to root_url
end
end
** ④ Create guest login button ** Add a guest login button to your favorite page. Please change the appearance as appropriate.
python
<%= link_to "Guest login", guest_login_path, method: :post %>
Recommended Posts