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:
Book.where(purchases: 20..)
# Returns a collection of records with purchases from 20 and upwards.
Book.where(purchases: ..20)
# 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:
class User
# ...
validates_length_of :first_name, in: 20..
end
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:
class User
# ...
validates_length_of :first_name, within: 20..
end
In a similar example, let's look at how we would use Active Model validations
along with the :inclusion
option:
class User
# ...
validates :age, inclusion: { in: proc { (25..) } }
end
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:
If this blog was helpful, check out our full blog archive.