[ACCEPTED]-Rails validation method comparing two fields?-ruby-on-rails-3

Accepted answer
Score: 16

My best guess is you need your method to 7 look like this:

private

def start_must_be_before_end_time
    errors.add(:start_time, "must be before end time") unless
        start_time < end_time
end 

(Also, notice the < rather 6 than > (or change to if and >=)

If this doesn't 5 work then you should also check that start_time and 4 end_time are being defined correctly in the controller 3 as there can be funny things happen if the 2 time is created across more than one form 1 element.

Score: 6

You need to check for presence yourself 12 (and skip the validation step if not present).

def start_must_be_before_end_time
  return unless start_time and end_time
  errors.add(:start_time, "must be before end time") unless start_time < end_time
end

Prints 11 either "must be a valid date/time" OR "start 10 time must be before end time".

Alternative

def start_must_be_before_end_time
  valid = start_time && end_time && start_time < end_time
  errors.add(:start_time, "must be before end time") unless valid
end

Prints 9 "start time must be a valid date/time" AND 8 "start time must be before end time" if 7 start_time or end_time isn't set.

Personal 6 preference for the first, since it only shows 5 what the user did wrong. The latter is like 4 many websites which just load off 20 lines 3 of error text onto the user just because 2 the programmer thought it would be nice 1 to see every validation result. Bad UX.

Score: 3

Clean and Clear (and under control?)

I find this to be the clearest to read:

In Your Model

# ...

validates_presence_of :start_time, :end_time

validate :end_time_is_after_start_time

# ... 

#######
private
#######

def end_time_is_after_start_time
  return if end_time.blank? || start_time.blank?

  if end_time < start_time
    errors.add(:end_time, "cannot be before the start time") 
  end 
end

0

Score: 0

You can use validates_timeliness gem https://github.com/adzap/validates_timeliness

0

Score: 0

start_time.to_i < end_time.to_ishould fix it. You are trying to compare 2 datetime but for some reason it can't, so 1 convert them to int before comparing.

Score: 0

Ruby on Rails 7.0 supports validates_comparison_of like this

validates :start_time, comparison: { less_than: :end_date }

0

More Related questions