2015-09-05 115 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