Comparison Validate more than Numbers in Rails
As of Rails 7 we can now use comparisions in validations for more than just numbers!
Previously we could do this but only against an integer
class Procedure
validates :appointment_count, numericality: { less_than: 5 }
end
Now we can compare against many other types. Here is a quick example validating that an end date is further in the future than a start date.
class Procedure
validates :start_date, comparison: { greater_than: ->(_) { Date.current }
validates :end_date, comparison: { greater_than: :start_date }
end
Cool thing is you can pass a Proc or Symbol. A symbol can represent a method on the class. The Proc can represent anything. Its argument is the instance of the class.
For more info, check out this PR.
Tweet