title: Time range method not working in Rails 4/Ruby 2 app
body: <p>I need help troubleshooting a time range problem in a Rails 4/Ruby 2.0 application. In my Appointment model, I want to prevent users from making appointments outside of business hours, which are 6:30 a.m. to 9:00 p.m.  The model tracks appointment times in a column named appointment_date, which is of the DateTime data type.</p>
  
  <p>I tried to solve the problem by placing the following methods in the app/validators directory:</p>
  
  <pre><code>class DuringBusinessHoursValidator &lt; ActiveModel::EachValidator
  
  def validate_each(record, attribute, value)    
  unless value.present? &amp;&amp; during_business_hours(value)
  record.errors[attribute] &lt;&lt; 'must be during business hours (6:30 am - 9:00 pm)'
  end
  end
  
  def during_business_hours(time)
  # from http://stackoverflow.com/q/10090962/525478    
  Range.new(
  Time.local(time.year, time.month, time.day, 6, 30),
  Time.local(time.year, time.month, time.day, 21, 0)) === time
  end
  end
  </code></pre>
  
  <p>I put the following code in my Appointment model:</p>
  
  <pre><code>validates :appointment_date, during_business_hours: true
  </code></pre>
  
  <p>However, Rails throws the following error:</p>
  
  <pre><code>TypeError in AppointmentsController#update
  can't iterate from Time
  </code></pre>
  
  <p>When I remove one of the === signs in the method, Rails does not generate an error, but the code does not operate correctly.  When using ==, all appointments are restricted, even those that will occur between 6:30 am and 9:00 pm.</p>
  
  <p>I read another Stackoverflow post where someone reported a problem executing the aforementioned method with Ruby 2.0.  The person stated they solved the issue by "converting the range endpoints with .to_i, and then comparing with t.to_i."  So, I changed the code in the second method as follows:</p>
  
  <pre><code>def during_business_hours(t)
  
  t = Time.now
  
  Range.new(
  Time.local(t.year, t.month, t.day, 6, 30).to_i,
  Time.local(t.year, t.month, t.day, 21).to_i
  ) === t.to_i
  end
  end
  </code></pre>
  
  <p>However, that change does not work.  It creates the opposite problem: Rails allows all appointments, regardless of hour.</p>
  
  <p>Any ideas or suggestions for how I can troubleshoot further and solve the problem?  I'd appreciate any help!</p>