← til

Filtering records with endless ranges

April 11, 2019

Ruby 2.6 has added support for endless ranges, which means ranges no longer require the end argument.

Endless ranges can be used in Rails applications, to filter records that were created after a date, for example.

Before this, the most common way of doing that was:

User.where('created_at >= ?', 1.year.ago)

Or with a range, to avoid passing strings to where:

User.where(created_at: 1.year.ago..DateTime::Infinity)

With an endless range, this can be replaced with:

User.where(created_at: 1.year.ago..)

Unfortunately, this is currently not supported with the current stable version of Rails(5.2.3), but it will be supported in the next major release of Rails(6.0.0).

Speaking of next releases, it looks like the next minor version of Ruby(2.7.0) will come with support for beginless ranges.

When Rails adds support for that, filtering records older than a date will be pretty straightforward:

User.where(created_at: ..1.year.ago)
@shime_sh Hrvoje Šimić
0 kudos