An error occurred in the process of building a login system for the completion of the blog. http://localhost:3000/users/new In, after executing Signup, I was able to redirect to the User's Profile screen, but Profile and Logout are not displayed at the top of the page, and SignUp and Login are displayed instead.
(1) "logged_in?" Defined in app/helpers/sessions_helper.rb and described in layouts/application.html.erb is not valid. However, no error was found in the code description itself, and both the conditional branch and the logged_in? Method (*) were fired.
logged_in?App storing the method/helpers/sessions_helper.rb
module SessionsHelper
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
current_user.present?
end
end
(2) In the first place, sessions_helper.rb was not generated when "rails g controller sessions new" was executed. ・ ・ ・ This is to prevent "-CSS, JavaScript, Helper files are not automatically generated by rails g command, and these extra files cannot be created", so in "config/application.rb" below By describing, I intentionally did not automatically generate it, but instead created the sessions_helper.rb file by myself.
config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module HogehogeAppli
class Application < Rails::Application
#abridgement
config.generators do |g|
g.assets false
g.helper false
end
end
end
Probably, I expected that logged_in? Did not fire well due to (2) above. But, http://localhost:3000/sessions/new If you log in with (Login page), Profile and Logout are displayed normally, so you cannot understand why logged_in? Does not fire. I was wondering how to display Profile and Logout after SignUp.
The logged_in? method fired any problem, so the problem was different.
In the first place, the login state is ** to give an encrypted user ID to cookies in the user's browser is called login, and to keep it is called login state. (The same user ID matches between the browser and the server) **, and the mechanism is ** You can realize the login state by giving the user ID to cookies using the session method at the time of create. ** ** After Login (= domain name/sessions/new), Profile and Logout are displayed normally, but Signup (= domain name/users/new) is not displayed and Signup and Login are displayed instead.
I thought that focusing on this difference would lead to a solution, and found that the create action in users_controller.rb did not create a login state.
app/controllers/users_controller.rb
def create
@user = User.new(user_params)
if @user.save
#I added the following line so that the encrypted user ID is automatically generated in the cookies in the user's browser.
session[:user_id] = @user.id
redirect_to user_path(@user.id)
else
render :new
end
end
As a result, we succeeded in displaying Profile and Logout on the screen after Signup as shown in the attached image.
Recommended Posts