Rails 7.1 allows infinite ranges for LengthValidators and Clusivity validators

Ghouse Mohamed

Ghouse Mohamed

August 30, 2022

This blog is part of our  Rails 7 series.

Rails 7.1 adds support for infinite ranges for Active Model validations which use the :in, and :within options. It was already possible to query using infinite ranges in Active Record like so:

1Book.where(purchases: 20..)
2# Returns a collection of records with purchases from 20 and upwards.
3Book.where(purchases: ..20)
4# Returns a collection of records with purchases from 20 and below.

But the same idea of using infinite ranges in Active Model validations was limited in scope. Rails 7.1 extends this scope of usage by adding support for infinite ranges in Active Model validations. For example, validating the length of first_name without an upper bound for a User will be as simple as writing:

1class User
2    # ...
3    validates_length_of :first_name, in: 20..
4end

The length of the :first_name does not have an upper bound. As long as the length is greater than or equal to 20, it will remain valid.

The above example also holds true when using the :within option as well:

1class User
2    # ...
3    validates_length_of :first_name, within: 20..
4end

In a similar example, let's look at how we would use Active Model validations along with the :inclusion option:

1class User
2    # ...
3    validates :age, inclusion: { in: proc { (25..) } }
4end

The above example would validate the :age field such that, it's value needs to be 25 or above for the record to be valid.

Please check out the following pull requests for more details:

  1. Infinite ranges for LengthValidator
  2. Infinite ranges for Clusivity validator

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.