Easy Datetime Comparison With ActiveRecord and Rails
The following is a guest post by Stephen Chen and originally appeared on his blog. Stephen is a Flatiron School alumni. You can learn more about him here, or follow him on Twitter here. TL;DR: Instead of creating or hardcoding your own DateTime and Date objects, use built in ActiveSupport methods in your ActiveRecord queries. Using ActiveRecord is great because […]
Reading Time 1 min
TL;DR: Instead of creating or hardcoding your own DateTime and Date objects, use built in ActiveSupport methods in your ActiveRecord queries.
Using ActiveRecord is great because of all the built in functionality, but combine ActiveRecord with all the headaches that come with dates and datetime and it can get pretty intimidating. In most web applications that you build you’ll probably find yourself needing to filter a set of ActiveRecord objects by date, whether it is a date_created field or something else. These are a few things that made this extremely easy for me to understand. I’m not going to cover formatting datetime display because that is another post for another day.
Check the table
First of all, you want to inspect your database table schema and determine what type of field you are comparing against. Your ActiveRecord model can have either ‘date’ or ‘datetime’ data types so you’ll want to make sure you use the corresponding ‘Date’ or ‘DateTime’ Ruby classes. You can actually compare ‘Date’ and ‘DateTime’ objects against one another:
However if you don’t realize that you are comparing two different types of data you may get unexpected results in your application.
Use built in ActiveSupport methods
“Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails. All these additions have hence been collected in this bundle as way to gather all that sugar that makes Ruby sweeter.” – http://as.rubyonrails.org/
This is the documentation for the ActiveSupport DateTime methods: http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/DateTime/Calculations.html
And this is the documentation for the ActiveSupport Date methods: http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html
With ActiveSupport you can easily query your database with ActiveRecord like this:
Posted by Flatiron School / December 2, 2012
Learn to Code Python: Free Lesson for Beginners
Sabrina Hernandez: From Dental Tech to UX / UI Product Designer
After 7 years as a dental tech, Sabrina Hernandez was ready for a change. She enrolled in Flatiron School and has since pivoted into a career in UX / UI Product Design.