0

I am trying to validate what I thought would be fairly simple to do. I have two time_select attributes "start_time" and "end_time". I am simply trying to validate in the controller whether the end time entered by the user is equal to the start time or before the start time. There are no dates involved at all. I have a validation method below however it always errors no matter what is entered by the user.

Fairly new to rails and can't help but feel im missing something small. This validation should work shouldn't it?

class Casenote < ActiveRecord::Base
 validate :end_must_be_after_start

 belongs_to :servicelog
 default_scope { order(:id) }


 private

 def end_must_be_after_start
   if :start_time >= :end_time
     errors.add(:end_time, "must be after start time")
   end
 end

end

1 Answers1

2

You are comparing the two symbols :start_time and :end_time. You need to be comparing the two attributes start_time and end_time.

def end_must_be_after_start
  if start_time >= end_time
    errors.add(:end_time, "must be after start time")
  end
end
Kristján
  • 18,165
  • 5
  • 50
  • 62
  • Looks like my other "end" got cutoff, it is now added for clarity. – NinjaBranDizzle Sep 21 '15 at 16:22
  • I was under the impression that these symbols took in the submitted value and validated them. How might I extract these submitted values and compare them within the model? Is the model the incorrect place to be comparing these? – NinjaBranDizzle Sep 21 '15 at 16:30
  • When a model object is created those values are methods in that model. If you did `model = Model.new(foo: bar, bar: foo)`, to get the value of foo or bar it would be `model.foo` -> bar `model.bar` -> foo. So, the model is the best place to check this. Every time a model is created or saved this validation will run. – nzajt Sep 21 '15 at 17:22
  • Would it be possible to request an example within the context of my situation? Im still fuzzy on how to implement the above code in my validation. – NinjaBranDizzle Sep 21 '15 at 17:53
  • @NinjaBranDizzle It sounds like you'd benefit from some reading. Check out [Active Record Basics](http://guides.rubyonrails.org/active_record_basics.html) and [Custom Validations](http://guides.rubyonrails.org/active_record_validations.html#custom-methods). – Kristján Sep 21 '15 at 18:06
  • Was looking for a simple solution, but I will give these a read. Thank you for your time and response. – NinjaBranDizzle Sep 21 '15 at 18:35
  • The simple solution is to learn the framework :) That'll solve your problems faster and better in the long run than asking the internet to write code. – Kristján Sep 21 '15 at 18:45