0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Railsで日付比較の検索の書き方

Last updated at Posted at 2020-10-27

Ruby2.7.1
Rails6.0.3.3
で確認

久しぶりにRailsでDBの検索処理を書いていて日付の比較の検索ってどう書くんだと調べていたのでメモ書き。
調べてるとたいてい、SQLを書くかArel使うかみたいのばっかで他に無いのかと調べていたら下記のような書き方でもいけた。

[0] pry(main)> User.where(created_at: ..DateTime.now)
  User Load (0.7ms)  SELECT `users`.* FROM `users` WHERE `users`.`created_at` <= '2020-10-27 14:41:26.943067'
[
    [0] #<User:0x000055861898f208> {
                   :id => 1,
           :created_at => Tue, 27 Oct 2020 14:18:54 JST +09:00,
           :updated_at => Tue, 27 Oct 2020 14:18:54 JST +09:00,
    }
]

逆は

 User.where(created_at: DateTime.now..)
  User Load (0.5ms)  SELECT `users`.* FROM `users` WHERE `users`.`created_at` >= '2020-10-27 14:52:57.534880'

へぇって感じ。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?