Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Can't assign blank values to virtual password attributes #10793

Closed
railstutorial opened this Issue May 30, 2013 · 6 comments

Comments

Projects
None yet
4 participants

Consider a standard User class with password and password confirmation, as in

class User < ActiveRecord::Base
  before_save { email.downcase! }
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
                    format:     { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password_confirmation, presence: true
  validates :password, length: { minimum: 6 }
end

With such a model, it is apparently not possible to assign blank values to the password or confirmation attributes. For example, with the User model shown, we can see the problem with a console session:

>> user = User.new(name: "Example User", email: "user@example.com",
?>                 password: "foobar", password_confirmation: "foobar")
>> user.password = "  "
=> "  "
>> user.password
=> "foobar"

As we can see, the password hasn't changed, despite the assignment. As far as I can tell, this happens with nil and whitespace, i.e., objects for which obj.blank? is true. In particular, nonblank values do work:

>> user.password = "bazquux"
=> "bazquux"
>> user.password
=> "bazquux"
Member

steveklabnik commented May 30, 2013

I have an outstanding pull request that changes some of this.

Awesome, good to hear it.

Contributor

al2o3cr commented May 30, 2013

@railstutorial - it appears this behavior (not updating password when the new value is blank) was deliberately introduced in #9535 (in particular, right here).

#10694 will still do the same thing...

Owner

rafaelfranca commented May 30, 2013

This seems expected behavior to me

Thanks for the comments. I was worried it might have been introduced intentionally. I find the new behavior confusing, as have several readers of the book, but I've already worked around it in the latest version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment