Using Date Ranges in Rails Queries

When working with dates in Rails, it’s common to want to find records that fall within a certain range of dates. For example, you might want to find all orders placed between two dates, or all events scheduled for a certain week.

One way to specify a date range in a Rails query is to use the BETWEEN operator, like this:

1
Order.where(created_at: start_date..end_date)

This will generate a SQL query that looks something like this:

1
SELECT * FROM orders WHERE created_at BETWEEN '2022-01-01' AND '2022-01-31'

However, there’s a catch: the where_values_hash method in ActiveRecord does not include ranges in the hash of conditions it returns. This means that if you want to inspect or modify the conditions in a relation, you may not be able to work with date ranges directly.

If you need to perform more complex queries involving date ranges, you can use SQL fragments to specify the conditions directly. For example:

1
2
Order.where("created_at BETWEEN ? AND ?", start_date, end_date)
This will generate a SQL query that looks similar to the previous examples, but uses placeholders to substitute the date values:
1
SELECT * FROM orders WHERE created_at BETWEEN '2022-01-01' AND '2022-01-31'

In general, it’s a good idea to use the most concise and readable representation of a date range in your queries, while keeping in mind the limitations of ActiveRecord’s condition hash.