Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1.1 has_secure_password digest can't be blank

I have been playing around with has_secure_password and I ran into a problem. My test for the create action in my UsersController was not working passing. So I started playing around in the console and realized that the password was not being converted to a has and saved in password_digest field.

When I try to create a user from the console the following happens.

irb(main):031:0> u = User.new(:email => "[email protected]", :password => "test", :password_confirmation => "test")
=> #<User id: nil, email: "[email protected]", password_digest: nil, created_at: nil, updated_at: nil>
irb(main):032:0> u.save
=> false
irb(main):033:0> u.errors
=> #<ActiveModel::Errors:0x00000100cde500 @base=#<User id: nil, email: "[email protected]", password_digest: nil, created_at: nil, updated_at: nil>, @messages={:password_digest=>["can't be blank"]}>

I am not sure what I am doing wrong. It looks like the password_digest attribute never gets assigned. If I create a user object with no attributes and assign each attribute individually I get the same error.

Here is my model

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

Thanks for the help in advance.

Alex Shenoy

like image 581
Alex Shenoy Avatar asked Feb 03 '23 12:02

Alex Shenoy


1 Answers

I had the same symptom, a message that the password_digest cannot be blank. The problem I had was that I had set this in the user.rb:

  attr_accessor :password

This prevented the method password= from being called (see secure_password.rb)

  # Encrypts the password into the password_digest attribute.
  def password=(unencrypted_password)
    @password = unencrypted_password
    unless unencrypted_password.blank?
      self.password_digest = BCrypt::Password.create(unencrypted_password)
    end
  end

and thus the value was never set for the password_digest.

For me, the fix was to remove the attr_accessor line.

like image 96
justingordon Avatar answered May 30 '23 09:05

justingordon