Rubynor logoGå hjem

Rails code

Rails howto: query within dates

  • Ole Morten Amundsen
1. mars, 2020

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: :from_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:

And I found the relevant ActiveRecord documentation here:

What is the shareholders book,

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.

Rails, investor, oppstartsbedrift