Rails code
Start-up company

Rails howto: query within dates

Working on an online shareholders book, Investorbok, I learned this not so well-known trick that helps me find records within a date range.

scope :of_shares_at, ->(shares_at) { where("period @> date ? ", shares_at) }

Notice the @>

In your schema migration you add this:

create_table :my_models do |t|
t.daterange :period

I confused this for a while with interval, introduced in Rails 5.2, but daterange has been around since 4.2, I just hadn't discovered it or too busy searching for better ways...

Solving the same problem without daterange:

t.date :from_date
t.date :to_date

and the query

scope :of_shares_at, ->(shares_at) { where("from_date < ? AND to_date > ?", shares_at) }

Not that bad, just two columns instead of one.

This is where I learned about it, through a PostgreSQL types blog post series: https://tapoueh.org/blog/2018/04/postgresql-data-types-ranges/

And I found the relevant ActiveRecord documentation here: https://apidock.com/rails/v5.2.3/ActiveRecord/ConnectionAdapters/PostgreSQL/ColumnMethods/daterange

What is the shareholders book, Investorbok.no?

Launching soon, it'll be a free service to help primarily Norwegian entrepreneurs, company owners and shareholders.

It'll keep track of founding, fund raising, share splits, share conversion, transfers (buy/sell), share class, dividends and more.