LoginSignup
4
7

More than 3 years have passed since last update.

[Ruby]今日・昨日・今週・今月のレコードを抽出する。

Last updated at Posted at 2019-06-19

概要

自分用のメモです。
データベース内のレコードのデータを今日・昨日・今週・今月の4パターンで取得し、それぞれ表示する必要があったので、そのやり方について記載します。
(レコードのカラムにはTimestampの「created_at」があることが前提です。)

やり方

1.今日のデータの抽出

@hoge = Hoges.all # @hogeにレコードの全データを代入
    @hoge.each do |hoge| # each文でレコードを分ける。
      if (hoge[:created_at].to_s.match(/#{Date.today.to_s}.+/)) 
    # Date.todayは、今日の年月日を取得できる。matchメソッドを使用し、hogeのレコード内に今日の年月日があるかどうか確認。
    # to_sで文字列に変換しているのは、matchメソッドは文字列にしか適用できないため。
        @data += hoge[:name] + "_" + hoge[:weight] # レコードが今日に相当すれば、@dataに名前と体重を代入。
      end
(メモ) 
# hoge[:created_at]がJSTになっていない場合は、以下のようにしてJSTに変更できる。
hoge_jst = hoge[:created_at].in_time_zone('Tokyo')

2.昨日のデータの抽出

# 今日のデータ取得の方法とほぼ同じです。
 @hoge = Hoges.all 
    @hoge.each do |hoge| 
      if (hoge[:created_at].to_s.match(/#{Date.yesterday.to_s}.+/)) 
    # Date.yesterdayは、昨日の年月日を取得できる。
        @data += hoge[:name] + "_" + hoge[:weight]
      end

3.今週のデータの抽出

 @hoge = Hoges.all 
 this_week = Date.today.all_week # all_weekをDate.todayに適用すると、今週の年月日データを取得できる。
    @hoge.each do |hoge| 
     if (this_week.include?(Date.parse(hoge[:created_at].to_s)))
    # 今週の日にちの中にhoge[:created_at]の年月日が含まれていれば、trueを返す。
    # parseメソッドは、this_weekとhoge[:created_at]のclassを合わせるために使用。
    # (this_weekはDateクラス, hoge[:created_at]はTimeWithZoneクラスのため)
        @data += hoge[:name] + "_" + hoge[:weight]
     end

4.今月のデータの抽出

# 今週のデータ取得の方法とほぼ同じです。
 @hoge = Hoges.all 
 this_month = Date.today.all_month # all_monthをDate.todayに適用すると、今月の年月日データを取得できる。
    @hoge.each do |hoge| 
     if (this_month.include?(Date.parse(hoge[:created_at].to_s)))
    # 今月の日にちの中にhoge[:created_at]の年月日が含まれていれば、trueを返す。
        @data += hoge[:name] + "_" + hoge[:weight]
     end

以上です!何か間違い等あれば指摘いただけると幸いです。

参考(非常に助かりました。)

すぐ忘れるので、RubyとRailsの日付操作周りについてまとめました
https://qiita.com/ykyk1218/items/d5086dcb7618d4f918ec

Railsでの日付操作でよく使うものまとめ
https://qiita.com/mmmm/items/efda48f1ac0267c95c29

4
7
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
4
7