Numerical validation using `validates_comparison_of` ๐Ÿ™Œ๐Ÿผ

Do you know you can use validates_comparison_of with Rails 7.0 that provides a way to easily validate comparisons with another value, proc, or attribute?

There are multiple helpers available -

  1. greater_than
  2. less_than
  3. greater_than_or_equal_to
  4. less_than_or_equal_to
  5. equal_to
  6. other_than

It works with -

  1. Numeric Values
  2. Dates
  3. String

You can use more than one comparison option at the same time ๐Ÿ”ฅ

Reference - Rails PR #40095 by Rachael

Code Snippet -

# Before
class Requirement < ApplicationRecord
  validates :min_budget, :max_budget, presence: true
  validate :min_max_budget

  private
  def min_max_budget
    if max_budget < min_budget
      errors.add(:max_budget, 'must be greater than min budget')
    end
  end
end

# With Rails 7.0
class Requirement < ApplicationRecord
  validates :min_budget, :max_budget, presence: true

  validates_comparison_of :max_budget, greater_than: :min_budget
  # OR
  validates_comparison_of :min_budget, less_than: :max_budget
end