You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.View Our Jobs Report
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:
Blog Post Author
Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.
Find the perfect course for you across our in-person and online programs designed to power your career change.
Connect with students and staff at meetups, lectures, and demos – on campus and online.
Have a question about our programs? Our admissions team is here to help.