LoginSignup
6
2

More than 3 years have passed since last update.

【Ruby on Rails】ランキング表示(合計、平均値)

Posted at

目標

ランキングの表示

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

※ ▶◯◯ を選択すると、説明等が出てきますので、
  よくわからない場合の参考にしていただければと思います。

  • controllerとviewのみ変更
  • userモデル
  • postモデル(:body, :score)
  • いいね機能実装
  • Google Natural Language APIによるコメント感情分析導入済み(投稿の点数付け)

※今回の方法では、
数値がない(いいねが押されていない、平均値がない)ユーザーは
表示されません。

controller

コントローラーさえできればできたも同然です!

平均値のランキング:app/controllers/users_controller.rb
  def rank
    @users = User.
              find(Post.
                    group(:score).
                    order('avg(score) desc').
                    pluck(:user_id)
                  )
  end

補足
@users = User.find( ):@userにUserモデルから以下の条件で取得した値を入力
・Post.group(:score):Postモデルからscoreカラムでグループ分け
・order('avg(score) desc'):scoreの平均順で降順並び替え
・pluck(:user_id):上記値のuser_idがあるものを全て配列

合計のランキング:app/controllers/posts_controller.rb
  def rank
    @posts = Post.
              find(Favorite.
                    group(:post_id).
                    order('count(post_id) desc').
                    pluck(:post_id)
                  )
  end

補足
@posts = Post.find( ):@postにPostモデルから以下の条件で取得した値を入力
・Favorite.group(:post_id):Favoriteモデルからpost_idカラムでグループ分け
・order('count(post_id) desc'):post_idの個数で降順並び替え
・pluck(:post_id):上記値のpost_idがあるものを全て配列

view

下記のようにeach降順順で表示可能

<% @users.each do |user| %>
<% end %>
<% @posts.each do |user| %>
<% end %>

Kaminariを使用する場合

前にKaminari.paginate_array( )、後ろに.page(params[:page])をつければOK

@posts = Kaminari.paginate_array(Post.find(Favorite.group(:post_id).order('count(post_id) desc').pluck(:post_id))).page(params[:page])

参考サイト

Railsでお手軽ランキング機能
【Rails】ランキング機能の実装

6
2
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
6
2