2016-07-23 40 views
0

我遵循了关于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应该是用户的电子邮件。我错过了什么?

回答

1

首先你的一些代码,似乎是错误的

class ApplicationController < ActionController::Base 
    protect_from_forgery with: :exception 
    before_action :authentication_required 

    def authentication_required 
    redirect_to login_path if !logged_in? 
    end 

    def logged_in? 
    current_user.present? 
    end 

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

您正在创建一个辅助方法,这样你就不需要调用@current_user,只需调用current_user

而且,session[:user_id]不是email。这是身份证。您正在使用它找到User.find(session[:user_id])的用户。这与User.find(1)相同。

#<User:000s500r00k000h0>是对您分配给@current_user的用户对象的引用,数字是存储它的内存空间。

您只需调用您希望为登录用户显示的方法。如果email然后emailusername然后username

+0

谢谢!我试图找出这个'current_user'问题的原因是:本教程演示了安全的登录/注销以及如何保持某些信息的私密性(或者防止黑客攻击) - 但是'current_user'而不是'user.email'(尽管老实说,我还没有足够的理解这一切)。教程将显示登录用户的电子邮件。 – YCode

+0

无论如何,电子邮件只会显示给登录用户,因为before_action:authentication_required会重定向任何未登录的人。 –

1

只需更改<p>You are logged in as: <%= @current_user %></p><p>You are logged in as: <%= @current_user.user_id %></p>。你目前看到的#<User:000s500r00k000h0>只是用户对象本身的表示。

1

您应指定您从@current_user这样想:

<p>You are logged in as: <%= @current_user.email %></p> 

如果不指定,Rails会刚刚抛出什么@current_user是。