Ruby - Validates field presence after create

Viewed 40

Is it possible to validate a field for presence after the initial creation? I want to make phone number mandatory if the user wants to update their account after signing up.

  validates :phone, presence: true, if: .....

if I use on: :update I can no longer authenticate until the field is filled

1 Answers

There are many ways to accomplish this task assuming it is a normal Rails model backed by a DB table. Off the top of my head you can do:

validates :phone,
          presence: true,
          if: Proc.new{ |model| model.id.present? }

Or more to the point and doesn't fail if you assign an ID before saving:

validates :phone,
          presence: true,
          if: Proc.new{ |model| model.persisted? }
Related