2015-09-05 110 views
0

我正在按照railstutorial.org上的教程添加帐户激活。 如果我从控制台(其中邮件显示在服务器日志中)复制链接,则通过访问生成的链接进行帐户激活有效。但是,您可以在http://localhost:3000/rails/mailers/user_mailer/account_activation下找到的邮件预览包含另一个错误链接。问候中的名字相符,因此只有标记是错误的。请在下面找到一些相关的代码:用户激活邮件预览,错误的激活链接

测试/邮寄/预览/ user_mailer_preview.rb:

class UserMailerPreview < ActionMailer::Preview 
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/account_activation 
    def account_activation 
    user = User.last 
    user.activation_token = User.new_token 
    UserMailer.account_activation(user) 
    end 

邮件html.erb:

<p>Hi <%= @user.name %>,</p> 
<p>Welcome. Click below to activate account </p> 
<%= link_to "Activate", edit_account_activation_url(@user.activation_token, email: @user.email) %> 
在用户模式

attr_accessor :remember_token, :activation_token 
     before_save :downcase_email 
     before_create :create_activation_digest 
    def User.digest(string) 
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : 
                BCrypt::Engine.cost 
    BCrypt::Password.create(string, cost: cost) 
    end 
def User.new_token 
    SecureRandom.urlsafe_base64 
    end 

    private 
    # Converts email to all lower-case. 
    def downcase_email 
     self.email = email.downcase 
    end 

    # Creates and assigns the activation token and digest. 
    def create_activation_digest 
     self.activation_token = User.new_token 
     self.activation_digest = User.digest(activation_token) 
    end 

和控制器:

def create 
    @user = User.new(user_params) 
    if @user.save 
      @user.send_activation_email 
     flash[:info] = "Please check your email to activate your account." 
     redirect_to root_url 
    else 
     render 'new' 
    end 
    end 

您知道为什么在邮件预览中会生成一个与serverlog中的标记不同的标记吗?

回答

0

有两件事可能会让你感到困惑。首先是两个电子邮件模板上的名称匹配可能仅仅是因为您为两个不同的用户存储了完全相同的名称。第二个原因是,每次访问http://.../account_activation时,都会在开发数据库中为第一个用户生成一个新的activation_token。

每对教程中的说明:

注意,清单10.16也将值赋给user.activation_token, 这是必要的,因为清单 10.12和10.13列出账户中激活模板需要一个账号激活令牌。

found at https://www.railstutorial.org/book/account_activation_password_reset#code-account_activation_preview