下面我有两个辅助方法。
helpers do
def logged_in?
!current_user.nil?
end
def current_user
@current_user ||= User.find(session[:user_id])
end
我使用这些方法来验证用户是否已登录,或者是否需要登录或创建帐户。在我的索引页面上,我有两条路线可以将我带到登录页面或创建用户页面。这些路线如下所示。
HTML查看
<html>
<head>
<title>Simple Meal Prep</title>
<link href="https://fonts.googleapis.com/css?family=Caveat"
rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/stylesheet.css" />
</head>
<body>
<h1 id="landing_page_title">Welcome to Cookbook</h1>
<h2 id="site_logline">A Simple App to keep track of your recipes</h2>
<br></br>
<a id="login_button" href="/login">Login</a> <route 1>
<br></br>
<a id="signup_button" href="/signup">Sign Up</a> <route 2>
</body>
对应的用户控制器路由
class UserController < ApplicationController
get '/user_home' do
if logged_in? then erb :"/users/user_home" else redirect '/' end
end
get '/login' do
if logged_in? then redirect to '/user_home' else erb :"/users/login"
end
end
end
我得到的错误是当我点击我的登录按钮时,我得到一个sinatra错误,声明&#34; ActiveRecord :: RecordNotFound at / login 无法找到没有ID的用户&#34;。看看来自sinatra的回溯,我不相信我的login_in?方法工作正常。我想知道是否有人对接下来采取的步骤或看到我没有看到的事情有任何建议。如果需要,我可以包含任何其他代码或模式。谢谢。
答案 0 :(得分:2)
使用find_by(id: session[:user_id])
代替find(session[:user_id])
。
find
会引发错误,或者找不到匹配的记录。 find_by
在这两种情况下都不会引发错误。
由于您的代码允许此查询的结果为nil(@current_user
变量将为nil,current_user
方法的返回值也将为nil),因此似乎此更改将解决你的问题。