Note that there are some explanatory texts on larger screens.

plurals
  1. PORails - Is a date between two dates?
    text
    copied!<p>I'm creating a system that needs to make sure planned "Trips" do not over lap. To do this I am trying to validate the start_date and end_date to make sure they are not within the start and end dates for another trip.</p> <pre><code>class TripdateValidator &lt; ActiveModel::EachValidator def validate_each(object, attribute, value) # Check value exists as end_date is optional if value != nil parsed_date = Date.parse(value) # is the start date within the range of anything in the db trips = Trip.where(['start_date &gt;= ? AND end_date &lt;= ? AND user_id = ?', parsed_date, parsed_date, object.user_id]) # overlapping other trips, aghhh object.errors[attribute] &lt;&lt; 'oh crap' if trips end end end </code></pre> <p>The date is coming from a type="date" field which is powered by jQuery UI Datepicker and contains the format 2011-01-01. This gets to rails as 2011-01-30 00:00:00 UTC which I don't fully understand.</p> <p>If I try to use Date.parse() on this value it gives the error:</p> <blockquote> <p>TypeError in TripsController#create</p> <p>$_ value need to be String (nil given)</p> <p>Rails.root:<br> /Users/phil/Sites/travlrapp.com<br> Application Trace | Framework Trace |<br> Full Trace </p> <p>app/models/trip.rb:29:in<br> <code>validate_each'<br> app/controllers/trips_controller.rb:75:in </code>create'<br> app/controllers/trips_controller.rb:74:in<br> `create' </p> </blockquote> <p>Whenever I run the query, nothing is returned. Could this be a date format issue, is my logic broken or am I doing something really stupid? Been stuck on this a while and google is no help.</p> <p><strong>Edit</strong> People are focusing on the Date.parse error but that is not the main problem. Where im stuck is that I don't understand how to do date comparisons when everything is in totally different formats.</p> <p>I have swapped Date.parse() for Chronic.parse() and now I am getting the following SQL queries generated:</p> <pre><code> SELECT "trips".* FROM "trips" WHERE (start_date &gt;= '2011-01-26 00:00:00.000000' AND end_date &lt;= '2011-01-26 00:00:00.000000' AND user_id = 19) </code></pre> <p>This returns nothing. The dates I am testing against are: </p> <p>start: 2011-02-17 00:00:00.000000 end: 2011-02-21 00:00:00.000000</p> <p>Seeing as I think dates are being formatted properly now it seems more like a logic problem. How the heck can I validate overlapping dates >.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload