Could not find user with id = 1

I have a current_user method for authentication.

application_controller.rb

 protect_from_forgery helper_method :current_user def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end 

but when I try to connect to the page, I get the following error:

 Couldn't find User with id=1 app/controllers/application_controller.rb:10:in `current_user' 

How to pass @current_user its default value, so if there is no user, it will be redirected to the login page.

Thanks for the help.

+4
source share
1 answer

It looks like your session contains old data, specifically a user ID (1) that no longer exists. Try to handle the RecordNotFound exception RecordNotFound by ActiveRecord and return zero:

 def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] rescue ActiveRecord::RecordNotFound end 

To redirect, you must add a second before_filter that validates the user and handles the redirection to the login path:

 before_filter :require_user def require_user redirect_to login_path unless current_user end 

Remember to skip require_user for your login action by adding skip_before_filter :require_login to which controller manages your authentication.

+12
source

Source: https://habr.com/ru/post/1386591/


All Articles