Rails 7 adds ComparisonValidator to ActiveRecord

Gaurav Varma

Gaurav Varma

October 5, 2021

This blog is part of our  Rails 7 series.

Rails Active Record Validation provides a convenient way to validate the state of an object before it is stored in the database. There are various built-in Active Record validations like presence, length, numericality and uniqueness.

By using numericality validator, we can validate an attribute to only have numeric values.

1# app/models/blog.rb
2class Blog < ApplicationRecord
3  validates :likes, numericality: true
4end

We can also use helpers like greater_than, greater_than_or_equal_to, equal_to, less_than, less_than_or_equal_to, other_than, odd, even with numericality validator but these work only on numbers.

1# app/models/blog.rb
2class Blog < ApplicationRecord
3  validates :likes, numericality: { greater_than: 1 }
4end

Previously for validating comparisons of dates we needed to write custom validators or use a gem like date_validator.

However, Rails 7 has added ComparisonValidator which provides a way to easily validate comparisons with another value, proc, or attribute. Let's assume we have a model Blog with an end_date attribute.

Before

If we want to validate the end_date attribute for the provided value or then we would need to write a custom validator or use a gem like date_validator.

1# Using date_validator gem
2class Blog < ApplicationRecord
3  # validate against provided value
4  validates :end_date, date: { after: Proc.new { Date.today } }
5  # validate against another attribute
6  validates :end_date, date: { after: :start_date }
7end

Rails 7 onwards

We can use ComparisonValidator to validate the comparison of the end_date attribute for a provided value.

1class Blog < ApplicationRecord
2  # validate against provided value
3  validates_comparison_of :end_date, greater_than: -> { Date.today }
4  # validate against another attribute
5  validates :end_date, greater_than: :start_date
6end

ComparisonValidator also provides helpers like greater_than, greater_than_or_equal_to, equal_to, less_than, less_than_or_equal_to and other_than.

Check out this pull request for more details.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.