我做了rails db:migrate:reset
和rails db:migrate
,然后访问localhost:3000
发现了错误
ActiveRecord::RecordNotFound in WelcomeController#index
Couldn't find User with 'id'=9
。
在此命令之前,我已将db从SQLite3更改为postgre以便在heroku上进行部署。
宝石文件
group :development, :test do
gem 'sqlite3', '1.3.13'
end
group :production do
gem 'pg', '0.20.0'
end
application_controller.rb
lass ApplicationController < ActionController::Base
protect_from_forgery with: :exception
private
def current_user
@current_user ||=User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def authorize
redirect_to new_session_path, alert: 'plz sign in or sign up' if current_user.nil?
end
def admin_authorize
redirect_to new_session_path,
alert: "Only for Admin!" unless current_user.admin
end
end
错误日志
Started GET "/" for 127.0.0.1 at 2019-02-27 15:39:23 +0900
Processing by WelcomeController#index as HTML
Rendering welcome/index.html.erb within layouts/application
Rendered welcome/index.html.erb within layouts/application (1.8ms)
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 9], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:6
Rendered shared/_navigation.html.erb (4.4ms)
Completed 500 Internal Server Error in 42ms (ActiveRecord: 0.1ms)
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=9):
app/controllers/application_controller.rb:6:in `current_user'
app/views/shared/_navigation.html.erb:14:in `_app_views_shared__navigation_html_erb__2712194429362090156_70209715304560'
app/views/layouts/application.html.erb:11:in `_app_views_layouts_application_html_erb__2819014747178102869_70209752482340'
答案 0 :(得分:1)
您应该在下面尝试
def current_user
@current_user ||=User.find_by_id(session[:user_id]) if session[:user_id]
end
find_by_id
是查找器方法,如果不存在通过会话提供的ID的记录,它将返回nil。
此外,您可以添加过滤器以使会话过期为session[:user_id] = nil
我在Rails API应用中遇到了以下情况,
User.find_by_id(session[:user_id]) || redirect_to(new_user_session_url)