1

I have working on a Ruby on Rails application and have a problem. I've user model in my domain and it has a has_secure_password field like this:

class User < ApplicationRecord
    validates :name, presence: true

    has_secure_password
    validates :password, presence: true
    validates :password, length: { in: 6..20, message: 'Password shoul be minimum 6 characters'}
end

And I save the user object with this function:

def self.create_with_params(email,name,password)
    user = User.new()
    user.provider= :mail
    user.name=name
    user.email=email
    user.password=password
    user.activate_status=false

    user.save(validate: true);

    return user;
end

That's ok too.

But when I want to update a field in my user model. I get validation error for password field.

@user = User.find_by(email: params[:email]) # this record has a valid password_digest field in database.
@user.name = 'John'
@user.save

puts @user.errors.full_messages

It prints:

"Password shoul be minimum 6 characters".

Note: I have password_digest field in my users table.

I think when I query users table password_digest field couldn't be filled in to password field on model.

Any suggestions?

1
  • If password is a virtual field you should only validate it when you need to. Commented Jun 7, 2017 at 22:16

1 Answer 1

3

I think when I query Users table password_digest field couldn't be filled in to password field on model.

Correct, the password is not stored, so when you query User you don't get the password field, yet your model asks for it every time with:

validates :password, presence: true

So, you will need to provide password before saving @user to make it work, but i guess that is not what you want, so just remove that validation from your model,

You won't need to validate password every time, just upon creating, and that validation is done with has_secure_password.

Also, for the same reason, you will need to update length validation to:

validates :password, length: { in: 6..20, message: 'Password shoul be minimum 6 characters'}, allow_nil: true
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.