One minute
Comparison Validator to easily validate comparisons ๐งจ
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 -
- greater_than
- less_than
- greater_than_or_equal_to
- less_than_or_equal_to
- equal_to
- other_than
It works with -
- Numeric Values
- Dates
- 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
Read other posts
comments powered by Disqus