T. Weston Kendall T. Weston Kendall - 25 days ago 12
Ruby Question

How to use has_secure_password with field_with_errors

I am using has_secure_password to verify my user password and its confirmation. The problem I have is that when there are any errors, the fields are not being wrapped with a field_with_errors div. I know that I can add

validates_presence_of :password, :on => :create
validates_presence_of :password_confirmation, :on => :create

but that creates the following error message:

Password digest can't be blank.

Password can't be blank.

Password confirmation can't be blank

I would like to either make the has_secure_password wrap the fields with errors with a field_with_errors div or remove the "Password digest can't be blank." error altogether.


Answer Source

The SecurePassword module which has this functionality is quite simple and worth a look. Good news is that in the master branch (Rails 4) it does validates_presence_of :password, :on => :create which will solve your problem, but in the meantime you might want to mimic the has_secure_password method on the User model yourself.

class User < ActiveRecord::Base
  attr_reader :password
  attr_accessible :password # ...
  validates_confirmation_of :password
  validates_presence_of :password, on: :create
  include ActiveModel::SecurePassword::InstanceMethodsOnActivation

Also make sure bcrypt is loaded in Gemfile.

gem 'bcrypt-ruby', '~> 3.0.0', require: 'bcrypt'

Hope that helps.