0

I need to validate two dates in date time format that come from create new record form. Right now the form has drop downs for year, date, month, hour, minute. In the controller, I need to validate that the start date is not greater than end date and it will not let me compare it using the params[:start_date] > params[:end_date].

How can I properly validate that the start date is not larger than the end date when adding a new record to the database, I should be doing this in the model but I cannot figure out how you do it. Does anyone here has any examples I can look from?

Bagzli
  • 6,254
  • 17
  • 80
  • 163
  • See: http://stackoverflow.com/questions/992431/comparing-dates-in-rails. If you want more specific answer, could you please show us your form and controller? – BroiSatse Sep 17 '13 at 19:28

3 Answers3

1

Add custom validation to your model to verify that the start date is less than the end date. Something like this would work:

# app/models/my_model.rb
validate :dates_in_order

def dates_in_order
    errors.add(:start_date, "must be before end time") unless start_date < end_date
end
zeantsoi
  • 25,857
  • 7
  • 69
  • 61
  • I tried it and thought to be the right answer, but the error is thrown no matter what I do, even if the start date is less than end date, how come? – Bagzli Sep 17 '13 at 20:43
  • I've updated my code – give it a try now. Have you verified that the `start_date` is indeed less than the `end_date`? – zeantsoi Sep 17 '13 at 20:47
0
#some_model.rb

before_create -> {
  errors.add(:base, "Start date cannot be later than end date.") if start_date > end_date
}
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • How would i compare two datetime instead of the date? – Bagzli Sep 17 '13 at 20:02
  • 1
    @Bagzli, it shouldn't matter, so long as you're comparing similar datatypes. All you've specified is that you need to compare `params[:start_date]` with `params[:end_date]`. If both params are the same datatype, you should be able to evaluate them. – zeantsoi Sep 17 '13 at 20:15
0

Not what you're asking for, but may also be a way to handle this. People sometimes don't read the labels so closely.

before_create :confirm_dates_in_order

def confirm_dates_in_order
  start_date, end_date = end_date, start_date if start_date > end_date
end
Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
  • The poster is asking for _validation_, which this doesn't do. Moreover, simply reassigning variables is __not__ a good way to ensure that variables are being correctly assigned. – zeantsoi Sep 17 '13 at 20:13
  • 1
    Sure - that's why I wrote it is "Not what you're looking for". The other answers have the 'validation' covered. But, in some cases, being more forgiving is the way to go. Giving an error and making the user switch the two dates can be a bad user experience. A validation and form error may not always be the answer. – Mark Swardstrom Sep 17 '13 at 21:06