LoginSignup
37
28

More than 5 years have passed since last update.

Ruby(ActiveSupport)で、今月中といった範囲を一瞬で作成する方法

Last updated at Posted at 2015-04-08

今月作成された記事を検索する場合、今までは

time = Time.now
this_month = time.beginning_of_month..time.end_of_month
Article.where(created_at: this_month)

といった感じに書いていましたが、all_monthメソッドを使うと簡単に書けるようになるようです。

Article.where(created_at: Time.now.all_month)

すっきり!

他にもall_dayall_weekall_yearがあります。

Time.new(2015, 4, 6).all_day
=> 2015-04-06 00:00:00 +0900..2015-04-06 23:59:59 +0900

Time.new(2015, 4, 6).all_week
=> 2014-03-31 00:00:00 +0900..2015-04-06 23:59:59 +0900

Time.new(2015, 4, 6).all_month
=> 2015-04-01 00:00:00 +0900..2015-04-30 23:59:59 +0900

Time.new(2015, 4, 6).all_year
=> 2015-01-01 00:00:00 +0900..2015-12-31 23:59:59 +0900
37
28
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
37
28