为什么我的第二个验证邮件不起作用?

时间:2016-10-21 21:34:26

标签: ruby-on-rails

@user更新其电子邮件属性时,会发送第一封验证电子邮件,并始终以有效的激活链接结束。用户检查他们的电子邮件,单击该链接,并验证该帐户。

def update
  @user = User.find(params[:id])
    ...
    elsif !params[:user][:email].blank?
      if @user.authenticate(params[:user][:current_password])
        @user.update_attributes(email_user_params)
        if @user.save
           @user.create_activation_digest
           @user.deactivated
           @user.send_activation_email
           log_out
           flash[:info] = "Please check email dude"
           redirect_to root_url
        else
   ...

但是,当@user请求第二封验证电子邮件时:

class EmailResetsController < ApplicationController
    def new
    end

    def create
      @user = User.find_by(email: params[:email_reset][:email].downcase)
      if @user && !@user.activated?
        @user.send_activation_email
        flash[:info] = "Email sent with instructions"
        redirect_to root_url
      else
       flash.now[:danger] = "Email address not found"
       render 'new'
      end
    end
end

电子邮件被正确发送,但链接始终返回无效。

user.rb

#sends out email
def send_activation_email
    UserMailer.account_activation(self).deliver_now
end

def create_activation_digest
  self.activation_token  = User.new_token
  self.activation_digest = User.digest(activation_token)
end

def User.digest(string)
  cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                              BCrypt::Engine.cost
  BCrypt::Password.create(string, cost: cost)
end    

 # Returns a random token.
def User.new_token
    SecureRandom.urlsafe_base64
end

def authenticated?(attribute, token)
    digest = send("#{attribute}_digest")
    return false if digest.nil?
    BCrypt::Password.new(digest).is_password?(token)
end

#the mailer view
account_activation.html.erb
  <%= link_to "Activate", edit_account_activation_url(@user.activation_token,
                                                email: @user.email) %>

class UserMailer < ApplicationMailer
  default from: "noreply@example.com"

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end
end

class AccountActivationsController < ApplicationController

  def edit
    user = User.find_by(email: params[:email])
    if user && !user.activated? && user.authenticated?(:activation, params[:id])
      user.activate
      log_in user
      flash[:success] = "Account activated!"
      redirect_to user
    else
      flash[:danger] = "Invalid activation link"
      redirect_to root_url
    end
  end
end


:activation_token and :activation_digest are both columns in user.rb

1 个答案:

答案 0 :(得分:1)

好的,我解决了这个问题。问题是EmailResetsController通过:email而不是:id查找用户。