我遵循了关于Rails窗体(登录,注销)的教程。一切都很顺利,除了这一点:一旦用户登录后,页面底部应该会显示“您已经登录为”,后面跟着一个电子邮件地址,所以它会说,例如,“您已经以简登录@ aol.com”。代码恕不承担的这一行:如何让“current_user”(编码为`session [:user_id]`)显示用户的电子邮件,而不是一些奇怪的代码?
<p>You are logged in as: <%= @current_user %></p>
然而,我所得到的却是You are logged in as: #<User:000s500r00k000h0>
(不是一个确切的副本)
对于我的生活,我无法弄清楚这个数字是什么,为什么用户的电子邮件显示不出来,也开始排除故障:
current_user
在ApplicationController中定义:
class ApplicationController < ActionController::Base protect_from_forgery with: :exception
def authentication_required if !logged_in? redirect_to login_path end end
def logged_in? !!current_user end
def current_user @current_user ||= begin User.find(session[:user_id]) if session[:user_id] end end helper_method :current_user end
的user_id
应该是用户的电子邮件。我错过了什么?
谢谢!我试图找出这个'current_user'问题的原因是:本教程演示了安全的登录/注销以及如何保持某些信息的私密性(或者防止黑客攻击) - 但是'current_user'而不是'user.email'(尽管老实说,我还没有足够的理解这一切)。教程将显示登录用户的电子邮件。 – YCode
无论如何,电子邮件只会显示给登录用户,因为before_action:authentication_required会重定向任何未登录的人。 –