【问题标题】:Rails - Email Confirmation - RecordNotFound ErrorRails - 电子邮件确认 - RecordNotFound 错误
【发布时间】:2013-04-23 17:02:13
【问题描述】:

我希望在用户注册时发送一封电子邮件。此电子邮件应包含一个链接将帐户更改为完整用户。我希望此电子邮件链接成为安全令牌。

  • email_token 是每个用户随机生成的令牌
  • email_activation_token 是一个布尔值,表示用户是否完成注册

目前:我收到了要发送的电子邮件,但是当我点击链接时出现此错误。

ActiveRecord::RecordNotFound in UsersController#accept_invitation

Couldn't find User without an ID

链接已发送 http://localhost:3000/users/accept_invitation.P3Iu5-21nlISmdu2TlQ08w

user_controller.rb

class UsersController < ApplicationController
  def new
    @user = User.new
  end
  def create
    @user = User.new(params[:user])
    if @user.save
      UserMailer.registration_confirmation(@user).deliver
        redirect_to root_url, :notice => "Signed up!"
    else
        render "new"
    end

    def accept_invitation
        @user = User.find(params[:email_token])
        @user.email_activation_token = true
        redirect_to root_url, :notice => "Email has been verified."
    end
  end
end

registration_confirmation.html.haml

Confirm your email address please!

= accept_invitation_users_url(@user.email_token)

user.rb 模型

    class User < ActiveRecord::Base
      attr_accessible :email, :password, :password_confirmation

      attr_accessor :password
      before_save :encrypt_password
      before_save { |user| user.email = email.downcase }
      before_create { generate_token(:auth_token) }
      before_create { generate_token(:email_token) }

      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      VALID_PASSWORD_REGEX = /^(?=.*[a-zA-Z])(?=.*[0-9]).{6,}$/
      validates_confirmation_of :password
      validates :password, :on => :create, presence: true, format: { with: VALID_PASSWORD_REGEX }
      validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }

def generate_token(column)
  begin
    self[column] = SecureRandom.urlsafe_base64
  end while User.exists?(column => self[column])
end

end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 authentication email-validation


    【解决方案1】:

    您收到该错误是因为在您的 accept_invitation 方法调用中,用户模型上的 find 需要一个 id 并且您正在传递 email_token 参数。

    试试这个..

    def accept_invitation
      @user = User.find_by_email_token(params[:email_token])
      @user.email_activation_token = true
      @user.save
      redirect_to root_url, :notice => "Email has been verified."
    end
    

    【讨论】:

      【解决方案2】:

      在你的控制器中你正在做:

      User.find(params[:email_token])
      

      这将尝试查找 id 等于参数传入的电子邮件令牌的用户。我认为您确实在尝试做更多类似的事情:

      User.find_by_email_token(params[:email_token])
      

      如果找不到具有给定 id 的记录,find 方法将引发异常。您需要能够通过令牌找到或从令牌中获取记录的ID。

      【讨论】:

        猜你喜欢
        • 2014-07-18
        • 2013-04-21
        • 2017-02-01
        • 2013-04-23
        • 2013-04-22
        • 2018-04-30
        • 1970-01-01
        • 2012-12-25
        • 1970-01-01
        相关资源
        最近更新 更多