たばりばりスタイル

たばりばりスタイル

バリバリバリ⚡︎

Railsのscopeを使って今月や今週で絞って取得する

Model.today や Model.this_month みたいなスコープをよく使うので備忘録で残します。

今日、今週、今月のスコープは以下のように実装しています。

# 今日
scope :today, -> { where(created_at: Time.current.all_day) }
# 今週
scope :this_week, -> { where(created_at: Time.current.all_week) }
# 今月
scope :this_month, -> { where(created_at: Time.current.all_month) }

その他に使えそうな...

# 昨日
scope :yesterday, -> { where(created_at: Time.zone.yesterday.all_day) }
# 明日
scope :tomorrow, -> { where(created_at: Time.zone.tomorrow.all_day) }

# 先週
scope :last_week, -> { where(created_at: Time.current.last_week.all_week) }
# 来週
scope :next_week, -> { where(created_at: Time.current.next_week.all_week) }

# 先月
scope :last_month, -> { where(created_at: Time.current.last_month.all_month) }
# 来月
scope :next_month, -> { where(created_at: Time.current.next_month.all_month) }

# 今年
scope :this_year, -> { where(created_at: Time.current.all_year) }
# 去年
scope :last_year, -> { where(created_at: Time.current.last_year.all_year) }
# 来年 
scope :next_year, -> { where(created_at: Time.current.next_year.all_year) }

Arel で書くなら...

# between
scope :today, -> { where(arel_table[:created_at].between(Time.current.all_day)) }
# in
scope :today, -> { where(arel_table[:created_at].in(Time.current.all_day)) }

雑談

最近 all_day の存在を知りました。
これまでは all_day の実装と同じような beginning_of_dayend_of_day を使った実装をしていました。
(Rails って本当になんでもメソッド揃って便利です😌

    # Returns a Range representing the whole day of the current date/time.
    def all_day
      beginning_of_day..end_of_day
    end

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb#L288

以上です。