Ruby Rails 设计确认令牌为零

Ruby on Rails Devise Confirmation Token is nil

我有一个用户模型(由 $ rails g devise User 创建),它设置为使用可确认(在模型和迁移中)。

创建用户时未设置确认令牌(并且未发送确认电子邮件)。

这里是app/models/user.rb

class User < ActiveRecord::Base     
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable

  def password_required?
    super if confirmed?
  end

  def password_match?
    self.errors[:password] << "can't be blank" if password.blank?
    self.errors[:password_confirmation] << "can't be blank" if password_confirmation.blank?
    self.errors[:password_confirmation] << "does not match password" if password != password_confirmation
    password == password_confirmation && !password.blank?
  end

  # new function to set the password without knowing the current 
  # password used in our confirmation controller. 
  def attempt_set_password(params)
    p = {}
    p[:password] = params[:password]
    p[:password_confirmation] = params[:password_confirmation]
    update_attributes(p)
  end

  # new function to return whether a password has been set
  def has_no_password?
    self.encrypted_password.blank?
  end

  # Devise::Models:unless_confirmed` method doesn't exist in Devise 2.0.0 anymore. 
  # Instead you should use `pending_any_confirmation`.  
  def only_if_unconfirmed
    pending_any_confirmation {yield}
  end

    protected
    def confirmation_required?
      false
    end    
end

有什么想法吗?

那是因为您将 confirmation_required? 覆盖为始终 return false。

看看this

before_create :generate_confirmation_token, if: :confirmation_required?

仅当该方法 return 为真时才会生成令牌。

如果记录尚未确认,confirmation_required? 的默认行为是 return true。

def confirmation_required?
  !confirmed?
end

为了补充@nbermudezs 的回答,添加了这个 confirmation_required? 方法以防万一你想绕过某些用户的确认(例如,具有特殊促销代码的用户,或其他)

如果您不想有任何例外,我建议您简单地删除这些代码行或对其进行注释,这样您 return 就可以使用 devise_confirmable 的默认行为你似乎想要(和@nbermudezs 给的那个)

# def confirmation_required?
#   false
# end