Simple Gnome
Simple Gnome

Reputation: 23

Rails: has_secure_password override

I have followed Railscast episode 250 revised to create user authentication with has_secure_password which works well. However when I try to update the user profile, I obviously run into issues because it requires password and password confirmation to be present.

Obviously there is no way to overwrite this out of the box so I have created a file called secure_password.rb which I have put into my config/initializers folder and copied the content of the pre-existing file.

My question is this - is there any way to pass a conditional to this file to say if controller action update/edit then don't require password and password confirmation to be present?

My current code can be found below.

  def has_secure_password
    gem 'bcrypt-ruby', '~> 3.0.0'
    require 'bcrypt'

    attr_reader :password

    validates_confirmation_of :password
    validates_presence_of     :password_digest

    include InstanceMethodsOnActivation

    if respond_to?(:attributes_protected_by_default)
      def self.attributes_protected_by_default
        super + ['password_digest']
      end
    end
  end

Upvotes: 2

Views: 841

Answers (1)

Carl Ekerot
Carl Ekerot

Reputation: 2228

when password_confirmation is explicitly set to nil, the confirmation validation will not be checked. This is refered to in a Rails pull-request, which suggests having some conditional value to decide if password_confirmation should be required.

In Railscasts #250, I would simply remove the password_confirmation-field, and change the create-action in the Users-controller to the following:

def create
  @user = User.new(params[:user])
  @user.password_confirmation = nil  # Disables confirmation check
  if @user.save
    redirect_to root_url, :notice => "Signed up!"
  else
    render "new"
  end
end

Upvotes: 1

Related Questions