Justice Hirschi
Justice Hirschi

Reputation: 59

Rails 6.0 validate password presence on create and update for one type of user but only update for another

I have a User model with the following attributes:

 id: integer
 username: string
 email: string
 password_hash: string
 password_salt: string
 account_type: string
 ...

My goal is to validate a user's password on create and update.

When a user with account_type: 'a' gets created or updated I want to run validates :password, :password_confirmation, presence: true.

When a user with account_type: 'b' gets updated I want to validate the password and password_confirmation presence as true, but NOT when the user gets created.

If more code or a clearer explanation would help, please let me know. Thanks in advance.

Upvotes: 0

Views: 384

Answers (1)

Joel Blum
Joel Blum

Reputation: 7888

validates :password, :password_confirmation, presence: true, unless: -> { |user| user.account_type == 'b' && user.new_record? }

Upvotes: 1

Related Questions