Follow Along as I Stumble on the Path to Learning RoR

How to Validate End Date After Start Date

I had an Event model where I had to write a simple validation that made sure that the end date was after the start date.  Here’s how I did it:

# event.rb
validate :end_after_start
validates :start_date, :end_date, :presence => true

private
def end_after_start
  return if end_date.blank? || start_date.blank?
 
  if end_date < start_date
    errors.add(:end_date, "must be after the start date") 
  end 
 end



private

Advertisements

Comments are closed.