Rails model validation on create and update only

Ruby on-RailsValidationModel

Ruby on-Rails Problem Overview


If I want to have validation only on create, then I can do

validates_presence_of :password, :on => :create

But how do I say on create and update? I tried this but it didn't work:

validates_presence_of :password, :on => [ :create, :update ]

Do I have to define the validation two times?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

By default, the validations run for both create and update. So it should be just:

validates_presence_of :password

The :on key just allows you to choose one of them.

Solution 2 - Ruby on-Rails

Only write:

validates_presence_of :password

No need...

on => :create

Solution 3 - Ruby on-Rails

You can use this when you need to disable the validation on some specific operations, such as delete.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJakub ArnoldView Question on Stackoverflow
Solution 1 - Ruby on-RailsAlessandra PereyraView Answer on Stackoverflow
Solution 2 - Ruby on-RailsFJ.View Answer on Stackoverflow
Solution 3 - Ruby on-RailsEderson BadecaView Answer on Stackoverflow