Help us understand the problem. What is going on with this article?

昨日作成されたレコードを取得するwhereの書き方(Railsガイド写経)

More than 3 years have passed since last update.

  Railsガイド、Active Record クエリインターフェイス、2.3.2 範囲条件 の写経による、小ネタになります。

  顧客を表すClientというモデルがあり、昨日作成されたレコードを取得するActiveReocrdクエリは
以下のように書ける。

Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)

こういう 1.dayの使い方、カッコええやん。ちなみに1.dayは何かといえば、

irb> 1.day.class
=> ActiveSupport::Duration

ActiveSupport::Durationのオブジェクト。

テストデータを作成して上記を写経。上記の where から、以下のようなBETWEENが作成される。

irb> Time.now
=> 2017-02-24 13:08:05 +0900
irb> Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
  Client Load (0.7ms)  SELECT `clients`.* FROM `clients` WHERE (`clients`.`created_at` BETWEEN '2017-02-23 00:00:00' AND '2017-02-24 00:00:00')
=> #<ActiveRecord::Relation [#<Client id: 201, name: "顧客-01", created_at: "2017-02-22 19:31:36",  ・・・

ここまではRailsガイドに書いてあるとおり。
では、created_at:で指定している期間を、..から...に変え、

Client.where(created_at: (Time.now.midnight - 1.day)...Time.now.midnight)

とするとどうなるか。
やってみると、

irb> Client.where(created_at: (Time.now.midnight - 1.day)...Time.now.midnight)
  Client Load (0.7ms)  SELECT `clients`.* FROM `clients` WHERE (`clients`.`created_at` >= '2017-02-23 00:00:00' AND `clients`.`created_at` < '2017-02-24 00:00:00')
=> #<ActiveRecord::Relation [#<Client id: 201, name: "顧客-01", created_at: "2017-02-22 19:31:36", ・・・

と、ちゃんと期待どおり、BETWEENではなく、下限以上、上限未満のWHERE句が生成されました。

ActiveRecord、ほんま賢いわー。

jun68ykt
ときどき teratail で回答してます。
https://teratail.com/users/jun68ykt
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした