I'm having an issue with my rails authentication. I'm not using Devise. For whatever reason when I log in to the app everything is fine but when I try to redirect when creating a new account current_user is nil? Any advice?
User Model
class UsersController < ApplicationController
before_action :set_user, only: [:show]
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Welcome to the site"
redirect_to current_user
else
flash[:notice] = "There was a problem creating your account. Please try again."
render new
end
end
def new
@user = User.new
end
def show
@locations = current_user.locations
@appointments = current_user.appointments
end
def index
end
private
def set_user
@user = User.find_by_email(params[:id])
end
def user_params
params.require(:user).permit(:name, :email, :service, :provider, :password, :password_confirmation)
end
end
Session Controller
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to current_user
else
flash.now[:error] = "There was a problem authenticating."
render action: 'new'
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Signed out!"
end
Application controller
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
end
helper_method :current_user
Upon signing up, you created the user, but not the session. When you look for current_user, the session[:user_id] does not have a value.
Also, I think the current_user method is probably not visible to the model.
You can try something like this:
class UsersController < ApplicationController
before_action :set_user, only: [:show]
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Welcome to the site"
session[:user_id] = @user.id # <=====
redirect_to @user # <=====
else
flash[:notice] = "There was a problem creating your account. Please try again."
render new
end
end
...
end
You'll need session[:user_id] = user.id
before the redirect after saving the new user. You've not set it so session[:user_id]
is nil when you create a user
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.