LoginSignup
5
1

More than 5 years have passed since last update.

ActiveRecordから取得したデータを日付別のハッシュにする

Last updated at Posted at 2016-06-30

ありがちなコード

hash = {}
User.all.each do |u|
  date = u.created_at.strftime('%Y%m%d')
  hash[date] ||= []
  hash[date].push u
end
# {"20160601"=> [#<User:..>...], "20160602" => ... }

Enumerable#group_byを使う

hash = User.all.group_by{|u| u.created_at.strftime('%Y%m%d') }
# {"20160601"=> [#<User:..>...], "20160602" => ... }

Enumerableの機能であるため、ActiveRecordが関係ない場所であっても使える。
集計関数を使う時はActiveRecordのgroupで出来るのだが、それ以外の時はActiveRecordのgroupだけでは解決しにくいので書いてみた。

5
1
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
5
1