Vicky
Vicky

Reputation: 489

How to run "has_secure_password" in condition?

I am using rails 4. Then my model looks like this

class User < ActiveRecord::Base

  has_secure_password

  def checkup?
    #Some Condition which returns true or false
    self.attr == "apple"
  end
end

In this i want has_secure_password run with the checkup? condition. i tried all bellow possible ways.

Try 1

has_secure_password :if => checkup?

Try 2

  def checkup?
    if condition_fails?
      has_secure_password  
    end
  end

Any Help?

Upvotes: 1

Views: 327

Answers (1)

j-dexx
j-dexx

Reputation: 10416

So if you look at the source code via the docs. You can pass validations: false to has secure password. Then you simply need to reimplement them.

They are

validate do |record|
  record.errors.add(:password, :blank) unless record.password_digest.present?
end

validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED
validates_confirmation_of :password, allow_blank: true

So you end up with

class User
  has_secure_password(validations: false)
  validate do |record|
    record.errors.add(:password, :blank) if record.password_digest.blank? && checkup?
  end

  validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED, if: :checkup?
  validates_confirmation_of :password, allow_blank: true, if: :checkup?
end

Upvotes: 1

Related Questions