I'm kosuke, a rails beginner.
I'm learning rails and the usage of session
may be unclear, so I will summarize it as a memorandum.
The session is mainly used for the login function and can keep the login status. By holding a session, you can be treated as a registered user until you log out once you log in. (If you close the browser, it disappears.)
Without session functionality, you would have to keep logging in every time you navigate the page.
In order to implement the session, it is necessary to inform the browser of each user.
Define a method to grant a session somewhere.
In the code below, the user id
is given a session named " user_id ".
This will automatically create and save the encrypted user id in the user's browser. By saving the user id on the browser, the user information can be retained.
sessions_helper.rb
#Method to grant session
def log_in(user)
session[:user_id] = user.id
end
The code below is the action when implementing login.
If the user's password authentication is correct, I try to give the user a session
.
sessions_controller.rb
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in(user)
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
You can delete the session by changing the value of the given session [: user_id] to nil
or deleting it.
#Set the value to "nil"
session[:user_id] = nil
Or
#Delete the value
session.delete(:user_id)
You can use session to return the currently logged in user (if any).
sessions_helper.rb
#Represents the currently logged in user.
def current_user
if session[:user_id] #user_If you have a session called id, set it to "true"
User.find_by(id: session[:user_id])
end
end
ruby:xxx.html.er
#Show the name of the currently logged in user
<%= current_user.name %>
ruby:xxx.html.er
#Display a link to the name and user information of the currently logged in user.
<%= link_to current_user.name, user_path(current_user) %>
rails tutorial Chapter 8 Login, logout https://railstutorial.jp/chapters/log_in_log_out?version=4.2
Recommended Posts