ActiveRecord validations (complex)
This course covers ActiveRecord validation options beyond a basic presence check, using this project's real models and a scratch table. It starts with the four shapes of the length option and moves to scoped, case-insensitive uniqueness. It then covers format with shared patterns, numericality, inclusion, exclusion and confirmation. Later lessons add conditional rules with if:, unless: and on: contexts. They also cover custom validate methods that call errors.add, and several ways to read the errors object. The last lesson combines every option on one Article model.
What you'll learn
- ✓The minimum, maximum, in and is keys of the length option
- ✓Uniqueness with scope:, case_sensitive: false and a custom message:
- ✓format with shared patterns, and numericality limits including only_integer
- ✓inclusion, exclusion and confirmation checks
- ✓Conditional validations with if:, unless: and on: contexts
- ✓Custom validate methods and reading errors with of_kind?, added?, details and each
length: four shapes for one option
In ActiveRecord: model introduction, the lesson "Validations: a rule before saving" introduced validates as a rule Rails checks before it saves a record. It ended by saying the options, the ways a check can fail, and how to report failures to a user would get a course of their own. In ActiveRecord:…
Read the full lesson free →Curriculum
7 lessonslength: four shapes for one option
The length option's four keys, minimum, maximum, in and is, each with its own error message.
uniqueness: scoped, and case-insensitive on purpose
Scoping uniqueness to a group with scope:, ignoring capitalization with case_sensitive: false, and replacing the default message.
format beyond a slug, and numericality for numbers
Reusing format patterns for email and URLs, and checking numbers with numericality keys such as only_integer.
inclusion, exclusion, and confirmation
Restricting values with inclusion and exclusion lists, and matching two fields with confirmation: true.
if:, unless:, and on: contexts
Running validations conditionally with if: and unless:, and limiting them to create, update or custom contexts.
A custom rule, and reading errors deeply
Writing custom validate methods that call errors.add, then reading failures through of_kind?, added?, details and each.
Putting it together: a fully validated article
One Article model combining every option from the course, plus allow_nil and allow_blank for empty values.