91
87

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 5 years have passed since last update.

ActiveRecordでBETWEEN

Last updated at Posted at 2014-09-17
User.where(created_at: (1.days.ago)..(Time.now))
# SELECT "users".* FROM "users"  WHERE "users"."created_at" BETWEEN '2014-09-16 15:05:05.279232' AND '2014-09-17 15:05:05.279753'

# 同じ
User.where(created_at: [1.days.ago..Time.now])

# Arelを使う
User.where(User.arel_table[:created_at].in((1.days.ago)..(Time.now)))
# SELECT "users".* FROM "users"  WHERE "users"."created_at" BETWEEN '2014-09-16 15:08:32.972344' AND '2014-09-17 15:08:32.972610'

# Squeelを使う
User.where{created_at.in (1.days.ago)..(Time.now)}
# SELECT "users".* FROM "users"  WHERE "users"."created_at" BETWEEN '2014-09-16 15:06:01.120660' AND '2014-09-17 15:06:01.120867'

以下のようなSQLを書くAPIはなさそう?

-- 今日が有効期限内
SELECT "users".*
  FROM "users"
 WHERE "2014-10-10" BETWEEN stared_at AND ended_at

↓こう書けばいいんじゃない? っていう記事ならたくさんありました

date = Date.today
User.where{ stared_at.lte(date) & ended_at.gte(date) }

余談

利用しているRDB特有の機能を使って「今日」を使うことも出来ます。
例えばPostgreSQLならcurrent_date関数を使うと今日が取得できますが、以下のようにして使います。

User.where{ updated_at > `current_date`}                                                                                 
# SELECT "users".* FROM "users"  WHERE "users"."updated_at" > current_date

91
87
3

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
91
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?