Rails date validation pit falls

When ever you want to validate a date field against a time frame┬ádon’t forget to add context to it. For example I have the following class

Movie – name, release_date and collections

class Movie
  validates :release_date, presence: true
  validate :release_date_future?

  private

  def release_date_future?
    if release_date < Date.today
      errors.add(:release_date, "can't be in the past")
    end
  end
end

This Class looks absolutely legit. Let’s say I have a Movie object called Avengers endgame.

Movie.new(name: ‘Avengers endgame’, release_date: ’04-26-2019′).save

So far so good but when i want to update the `collections` at later point of time(after the movie got released) i can never do that because the Movie obj goes invalid (as it once again checks the release_date with current_date).

so the right thing to do is to add context to the date validation. Like we are interested in only while creation.

validate :release_date_future?, on: :create

Hope this helps.