微炭酸ログ

Ruby や Rails を中心に。

【Rails】ActiveRecord の where で Range を使う

Range でない書き方と並べて書くことで、覚えやすくしています。
beginless, endless の less の部分(..の端)に指定したカラムの値が来るイメージでしょうか。
でも結局、毎回 rails console で確認するのがよさそうではあります。

以下

Book.where('released_on <= ?', Date.current)
# -> SELECT "books".* FROM "books" WHERE (released_on <= '2021-06-03')
Book.where(released_on: ..Date.current)
# -> SELECT "books".* FROM "books" WHERE "books"."released_on" <= '2021-06-03'

Brakeman を使用している場合は、以下のようなパースエラーが出るかと思います。

== Errors ==

Error: app/models/book.rb:17 :: parse error on value ".." (tDOT2) Could not parse app/models/book.rb
Location: /Users/yoshida/.rbenv/versions/2.7.2/lib/ruby/gems/2.7.0/gems/racc-1.5.2/lib/racc/parser.rb:538:in `on_error'

その場合は、Brakeman を 5.0.1 にアップグレードしてから、かつ以下のように括弧でくくることで、パースエラーを回避できます。

Book.where(released_on: ..Date.current)
↓
Book.where(released_on: (..Date.current))

参考:Failure parsing Ruby 2.7 beginless range · Issue #1483 · presidentbeef/brakeman

以上

Book.where('released_on >= ?', Date.current)
# -> SELECT "books".* FROM "books" WHERE (released_on >= '2021-06-03')
Book.where(released_on: Date.current..)
# -> SELECT "books".* FROM "books" WHERE "books"."released_on" >= '2021-06-03'

より小さい

Book.where('released_on < ?', Date.current)
# -> SELECT "books".* FROM "books" WHERE (released_on < '2021-06-03')
Book.where(released_on: ...Date.current)
# -> SELECT "books".* FROM "books" WHERE "books"."released_on" < '2021-06-03'

より大きい

Range では「より大きい」を書くことはできませんので、以下のように書きます。

Book.where('released_on > ?', Date.current)
# -> SELECT "books".* FROM "books" WHERE (released_on > '2021-06-03')

参考