LoginSignup
1
0

More than 1 year has passed since last update.

ユーザーごとの学習時間の合計

Posted at

はじめに

この記事は筆者がスタディープラスのトレースをする際に、ユーザーの学習時間のランキングを表示するために書いたコードの備忘録になります。

実装

deviseの導入と基本となる投稿機能(記事内ではtweets)が完成している前提で進めます。

users_controller
#以下を追記
    def index
        user = User.all
        @arr = []
        user.each do |t|
            t.sum_time = t.tweets.sum(:time)
            @arr.push(t)
        end
    end

pushメソッドは配列(@arr)の末尾に要素を一つ追加してくれるメソッドです

app/views/users/index.html.erb
<h1>Users#index</h1>
<% @arr.each do |u| %>
    <%= u.email %>
    <%= u.sum_time %>
<% end %>

配列の中身を一つずつ表示していきます。この時点ではまだランキング順での並べ替えはできていません。

users_controller.rb
#以下を追記
        @rank = @arr.sort do |a,b| 
            if !a[:sum_time]
                1
            elsif !b[:sum_time]
                -1
            else 
                b.sum_time <=> a.sum_time
            end
        end

この記述を加えることで@rankという変数の中にランキングが格納されます。

おわりに

閲覧ありがとうございました。もっと短い書き方をご存じの方がいましたら教えていただければ恐縮です!

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