Ruby on Rails: validate when context is not given value

Viewed 657

I update record by passing context:

employee.attributes = employee_params
employee.save(context: :age_related_fields)

and I know that in model I can conditionally apply validation only for given context

validates :date_of_birth, on: :age_related_fields

but is there a way how to use negation in the :on condition? e.g.

validate date_of_birth when context is NOT :personal_fields.

1 Answers

There is a rejected pull request on rails for what you're looking for.

https://github.com/rails/rails/pull/30710

The same task also has a workaround though:

validates :title, presence: true, unless: -> { validation_context == :test }
# or in your case
validates :date_of_birth, unless: -> { validation_context == :age_related_fields }
Related