LoginSignup
0
0

More than 5 years have passed since last update.

既存データを集計してランキング化する

Posted at

同一のitem_idに異なった複数のuser_idが紐付いたデータがあります。
(人気がある商品ほど紐付いているuser_idの数が多い)

これをグループ化、カウントして多い順に並べ替えます。
key(item_id)だけ配列として取得します。

@keys = Have.group(:item_id).order('count_item_id desc').count('item_id').keys.first(10)

ランキング用に商品データを出力したいので
1つづつkeyでItemデータからfindして詳細項目を出力していきます。

@keys.each do |key|
item = Item.find(key)

参考URL

ActiveRecordでgroup Byしてカウントをして、カウント数でorderする

大変参考になりました。
ありがとうございました。

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