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

Akanksha Jain

By Akanksha Jain

on 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.

1class StockItem < ApplicationRecord
2  validates :quantity, numericality: { greater_than_or_equal_to: 50, less_than_or_equal_to: 100 }
3end
4
5StockItem.create! code: 'Shirt-07', quantity: 40
6#=> 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:

1class StockItem < ApplicationRecord
2  validates :quantity, numericality: { in: 50..100 }
3end
4
5StockItem.create! code: 'Shirt-07', quantity: 40
6#=> ActiveRecord::RecordInvalid (Validation failed: Quantity must be in 50..100)

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