Search code examples
ruby-on-railsrubydateactiverecordruby-on-rails-6

(Rails 6 specific) How to validate a date for future events only?


In rails 7 I could use the ComparisonValidator and make my life easier, but I have a project that is running rails 6.1.7.3 (to be exact). Scoured the internet but certain methods are deprecated with 10+ years old approaches and other ones require more complex workaround -- I'm curious if there's a simpler way to do this.

I'm doing a ticketmaster style project; I have a Concerts model, with a date attribute. The user can enter dates aren't in the past (and also ideally aren't today either).

I'm looking to do something similar to below basically but in a proper way that would work for Rails6. For example, Concert.first has date: "2023-06-17"; the code below doesn't work, it's just my way of showing what I'm looking for conceptually.

class Concert < ApplicationRecord
    
   validates :date, presence: true, comparison: {greater_than: Date.today}
    
end

Any step in the right direction or any thoughts in general would be immensely appreciated

EDIT: I've accepted spickermann's answer but added a small thing onto it, in my answer below. This is what I went with in my own project.


Solution

  • You can use a custom validation method in cases like these.

    validate :date_must_be_in_the_future
    
    private 
    
    def date_must_be_in_the_future
      errors.add(:date, "can't be in the past") unless date.future?
    end