Andrew Hendrie
Andrew Hendrie

Reputation: 6415

Ruby on Rails Devise Confirmation Token is nil

I've got a User model (created by $ rails g devise User) and it is set to use confirmable (in the model and migration).

When a User is created the confirmation token is not being set (and the confirmation email is not being sent).

Here's 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

Any ideas?

Upvotes: 3

Views: 1003

Answers (2)

Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 13949

To complement @nbermudezs answer, this confirmation_required? method was added to devise in case you want to bypass confirmation for some users (eg users with special promo code, or whatever)

If you don't want to have any exceptions, I suggest you simply remove those lines of code or comment them, so you return to the default behavior of devise_confirmable which is the one you seem to want (and the one given by @nbermudezs)

# def confirmation_required?
#   false
# end  

Upvotes: 2

nbermudezs
nbermudezs

Reputation: 2844

That's because you are overriding confirmation_required? to always return false.

Take a look at this

before_create :generate_confirmation_token, if: :confirmation_required?

The token is only generated if that method returns true.

The default behavior of confirmation_required? is to return true if the record hasn't been confirmed.

def confirmation_required?
  !confirmed?
end

Upvotes: 3

Related Questions