This blog is part of our Rails 5 series.
Active Record validation is a well-known and widely used functionality of Rails. Slightly lesser popular is Rails’s ability to validate on custom context.
If used properly, contextual validations can result in much cleaner code. To understand validation context, we will take example of a form which is submitted in multiple steps:
Let’s go through all the four validations one-by-one.
1. personal_info validation has
no context defined
(notice the absence of
Validations with no context
are executed every time
a model save is triggered.
Please go through all the triggers
2. education validation has
It is executed only
when a new object is created.
3. work_experience validation
and gets triggered for updates only.
are the only two pre-defined contexts.
4. final_step is validated using
a custom context named
Unlike above scenarios,
it needs to be
explicitly triggered like this:
valid? runs the validation
in given context
save would first call
in the given context
and persist the changes
if validations pass.
One thing to note here is that
when we validate using an explicit context,
Rails bypasses all other contexts
Now that we understand validation context, we can switch our focus to validate multiple context together enhancement in Rails 5.
Let’s change our contexts from above example to
For each step, we would want to validate the model with all previous steps and avoid all future steps. Prior to Rails 5, this can be achieved like this:
valid? takes only one context
at a time.
So we have to repeatedly
valid? for each context.
This gets simplified in Rails 5
to accept an array.
Our code changes to:
A tad bit cleaner I would say.