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.

Written byAkanksha Jain
Related blogs
- 01Rails 6.1 adds invert_where methodMay 4, 2021 · Chimed Palden
- 02Rails 6.1 adds delegated_type to ActiveRecordApril 6, 2021 · Akhil Gautam
- 03Rails 6.1 adds nulls_first and nulls_last to ArelMarch 9, 2021 · Berin Larson
- 04Rails 6.1 adds support for PostgreSQL interval data typeJanuary 26, 2021 · Akhil Gautam