Rails 6.1 adds support for validating numeric values that fall within a specific range using the `in:` option

Akanksha Jain

Akanksha Jain

April 14, 2021

This blog is part of our  Rails 6.1 series.

Before Rails 6.1, to validate a numerical value that falls within a specific range, we had to use greater_than_or_equal_to: and less_than_or_equal_to:.

In the example below, we want to add a validation that ensures that each item in the StockItem class has a quantity that ranges from 50 to 100.

class StockItem < ApplicationRecord
  validates :quantity, numericality: { greater_than_or_equal_to: 50, less_than_or_equal_to: 100 }
end

StockItem.create! code: 'Shirt-07', quantity: 40
#=> ActiveRecord::RecordInvalid (Validation failed: Quantity must be greater than or equal to 50)

In Rails 6.1, to validate that a numerical value falls within a specific range, we can use the new in: option:

class StockItem < ApplicationRecord
  validates :quantity, numericality: { in: 50..100 }
end

StockItem.create! code: 'Shirt-07', quantity: 40
#=> ActiveRecord::RecordInvalid (Validation failed: Quantity must be in 50..100)

Check out the pull request for more details on this feature.

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.