Rails 7.1 adds support for infinite ranges for LengthValidators

railsOctober 31, 2023Dotby Alkesh Ghorpade

Ruby 2.6 added support for an endless range, and the support for the beginless range was added in Ruby 2.7. Endless ranges can be used to represent a range of values that has no end value, while beginless ranges can be used to represent a range of values that has no start value.

The support for beginless or endless range needed to be added in Rails, especially for ActiveRecord validators.

Before Rails 7.1

Before Rails 6.1, you need to pass the less_than_equal_to, greater_than_equal_to, options to the numericality validators as shown below:

class User < ApplicationRecord
  validates :age, numericality: { greater_than_equal_to: 18, less_than_equal_to: 65 } 
end

If you try to pass a range, it would raise an error.

Rails 6.1 added support for a passing range to the ActiveRecord validators. Let's say you have a Rails application on the 6.1 version, where the length of the name attribute of a User model cannot be greater than 30, and there is no lower limit or bound for it. If you try to specify an infinite range, Rails will throw RangeError as below:

class User < ApplicationRecord
  validates_length_of :name, in: ..30
end

User.create!(name: "example"*5)
=> cannot get the minimum of beginless range (RangeError)

The ..30 is a beginless range. If you pass an endless range, Rails will throw a similar endless RangeError.

class User < ApplicationRecord
  validates_length_of :name, in: 5..
end

User.create!(name: "example"*5)
=> cannot get the maximum of endless range (RangeError)

In Rails 7.1

Rails 7.1 adds support for infinite ranges for LengthValidators. You can pass an infinite range to the in and within options of the LengthValidators.

class User < ApplicationRecord
  validates_length_of :name, in: ..30
end

User.create!(name: "a")
=> #<User:0x000000010a1d2fa8 id: 7, name: "a",.....

User.create!(name: "example"*10)
=> Validation failed: Name is too long (maximum is 30 characters) (ActiveRecord::RecordInvalid)

The ..30 is nothing but the range (-Float::Infinity..30) and 30.. is (30..Float::Infinity).

To know more about this feature, please refer to this PR.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at justin@shakacode.com or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right