Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

ActiveRecordでBETWEEN

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

umanoda
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