I have a navigation bar that is displaying a different set of links based off if the user is signed in or not. I have setup a logged_in? method within a conditional statement in order to accomplish this. The problem is after I click the log in button and successfully sign in. The system doesn't alter the navigation bar as expected. I have to refresh the page or click another link in order to get it to register.
application.html.erb
<% if logged_in? %>
<li><%= link_to "Oppurtunity", companies_path %></li>
<li><%= link_to "Pipeline", deals_path %></li>
<li><%= link_to "Tasks", tasks_path %></li>
<li><%= link_to "My Account", edit_user_path(current_user) %></li>
<li><%= link_to "Log Out", logout_path, method: :delete, class: 'btn btn-default navbar-btn' %></li>
<% else %>
<li><%= link_to "Log In", login_path, class: 'btn btn-default navbar-btn' %></li>
<li><%= link_to "Contact", new_contact_path %></li>
<% end %>
session_helper.rb
# Returns the current logged-in user (if any).
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
def logged_in?
!current_user.nil?
end
session_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
if user.activated?
# Log the user in and redirect to the user's show page.
log_in user
params[:session][:remember_me] == '1' ? remember(user) : forget(user)
redirect_to root_url(subdomain: user.subdomain), notice: "Logged in!"
else
message = "Account not activated."
message += "Check your email for the activation link."
flash[:warning] = message
redirect_to root_url
end
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out if logged_in?
redirect_to root_url(subdomain: false)
end
end
You set up the current_user
logic wrongly. While comparing any two objects you need to use ==
but you are using =
. Try changing the current_user
method to below
def current_user
if (user_id == session[:user_id]) #here
@current_user ||= User.find_by(id: user_id)
elsif (user_id == cookies.signed[:user_id]) #and here
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.