Rails where date is greater than given date query
In Rails, fetch records newer than a specific date with the where
method by passing a date comparison condition:
Time zones for more accurate date comparison
When operating with dates, Time.zone.now
replaces DateTime.now
for consistency in Rails application time zone settings:
Ranging across dates
Use Ruby's range syntax for grabbing records between two dates:
You can also generate an open-ended query by providing just the beginning of the range:
Inclusive date comparisons
Sometimes, you want to compare dates inclusively. Switch out >
for >=
in those cases:
Ensure your SQL syntax is Jurassic-Park-proof (as in, no raptors sneaking in through faulty gaps):
Real-World scenarios (your mileage may vary)
Tackling Time Zone Monsters
For applications fighting off time zone monsters across different regions, store timestamps in UTC and heroically convert them to the users' local time when displaying:
The correct path toward TimeWithZone success
Grab the current time in a set time zone:
Rails version supremacy
For the more recent Rails 5.1 and onwards, using named placeholders enhances readability and maintenance:
Caveats and Solutions
The Dreaded Daylight Saving Time
When DST wreaks havoc on your app, use Rails to your advantage:
A Database Full of Time Zone assumption is a Database Full of Despair!
Don't be fooled — databases may not use the same time zone as Rails. Use time zone aware attributes for safety:
Consistency (is key!) in time zone usage
Keep your time zones consistent. Mixing Time.zone.now
and DateTime.now
is like ordering a pineapple pizza - some people (or your code) really might not like it.
Was this article helpful?