ruby-on-rails - Heroku 上 Rails 应用程序的数据库迁移错误(找不到用户 ID)
问题描述
如果之前有人问过这个问题,我们深表歉意。使用我的 rails 应用程序,在开发中一切正常,但是在推送到 Heroku 时,我遇到了一个问题,它试图查找 ID 为“1”的用户,但数据库为空。我已经迁移、重置和播种了数据库,但仍然从 Heroku 日志中得到错误。
似乎问题出在我的 _userportal 部分嵌入在articles/index.html.erb 文件中,该文件调用了current_user 和logged_in?来自 ApplicationController 的方法。
似乎答案应该突然出现在我身上,因为它必须与发现 User.find(session[:user_id]) 有关。或者更确切地说,一旦推送到heroku,数据库就没有正确重置。在 heroku rails 控制台中,User.count 为 0,但应用程序正在尝试查找 ID 为“1”的用户。我不确定为什么会这样。
从heroku日志:
2019-05-23T00:02:43.803680+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9] Rendered articles/index.html.erb within layouts/application (8.5ms)
2019-05-23T00:02:43.803865+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9] Completed 500 Internal Server Error in 10ms (ActiveRecord: 2.0ms)
2019-05-23T00:02:43.805254+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9]
2019-05-23T00:02:43.805305+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9] ActiveRecord::RecordNotFound (Couldn't find User with 'id'=1):
2019-05-23T00:02:43.805348+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9]
2019-05-23T00:02:43.805403+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9] app/controllers/application_controller.rb:4:in `current_user'
2019-05-23T00:02:43.805405+00:00 app[web.1]: [fe18170f-fab4-4495-8fe2-b2502762afb9] app/controllers/application_controller.rb:11:in `logged_in?'
应用控制器.rb:
def current_user
if session[:user_id]
@current_user ||= User.find(session[:user_id])
else
@current_user = nil
end
end
def logged_in?
!!current_user
end
_userportal.html.erb:
<div class="container">
<div class="userportal">
<div class="sessionsection">
<% if logged_in? %>
Logged in as <%= current_user.username %>.
<br>
<br>
<%= button_to 'Log Out', logout_path, method: :delete, class: "btn btn-xs btn-danger" %>
<% else %>
<%= link_to 'Sign Up', signup_path %> or
<%= link_to 'Log In', login_path %>
<% end %>
</div>
<hr>
<div class="actionsection">
<%= link_to 'Create a post', current_user ? post_path : signup_path %>
<hr>
<%= link_to 'See All Posts', blog_path %>
</div>
</div>
</div>
Heroku 控制台:
irb(main):005:0> User.count
(1.7ms) SELECT COUNT(*) FROM "users"
=> 0
Heroku 应该将 current_user 设为 nil,并且未正确登录?
感谢所有的帮助!请告知我是否应该提供更多代码/信息。
更新:
修复是在 current_user 方法中。改变:
@current_user ||= User.find(session[:user_id])
至:
@current_user ||= User.find_by(id: session[:user_id])
工作!
解决方案
只需使用find_by(id: val)
它就会返回nil
而不是异常。
def current_user
if session[:user_id]
@current_user ||= User.find_by(id: session[:user_id])
else
@current_user = nil
end
end
如果会话中的用户 ID 不存在,那就是current_user
这样。nil
推荐阅读
- python - Openpyxl保存损坏的文件,android
- python - SQLAlchemy 和 pg8000 KeyError / Broken Pipe on Google App Engine with Postgresql
- javascript - 导入/导出 Javascript,动态创建按钮事件 onclick(ES6)
- rust - 为什么这会变成堆栈溢出?
- angular - Quill 编辑器在 Angular 8 应用程序中未按预期显示
- r - 提取haven_labelled向量的标签作为字符串向量
- javascript - jQuery延迟错误:无法读取udefined的属性'then'
- mongodb - 如何在 MongoDB 中聚合文档数组
- javascript - JS学习练习?
- ios - LineChartView 使用图表库 Swift