2016-04-04 4 views
1

私はFIFAゲームを保存しようとしており、ランキングシステムでスコアボードを設定しようとしています。ループで値を並べ替える

私はビュー内でロジックを使うべきではありませんが、コントローラでそれらを計算すると、メソッドのユーザーが指定されていないというエラーがレンダリングされます。しかし、私はそれをループに入れると、ユーザがループしたアイテムであるため、それを認識します。

アプリは既にゲームを保存して勝者を計算することができます。アプリは各ゲームにwinner_idloser_idを追加します。後でスコアボードで、私はどのくらい多くのゲーム 'winner_id'とloser_idのすべてのループに一致する現在のuser_idの数を数えます。これにより、データベースがきれいに保たれます。ゲームが削除されたときに勝敗としてカウントされるべきではないため、dbの勝敗を維持したくありません。

コントローラー:

class ScoreboardController < ApplicationController 
    def index 
     @users = User.all 
    end 
end 

VIEW:私は右のために、このリストを入れたいのですが

<div class="panel panel-default" style="margin-left: 10px; margin-right:10px"> 
    <!-- Default panel contents --> 
    <div class="panel-heading">Scoreboard</div> 

    <!-- Table --> 
      <table class="table"> 
      <thead> 
       <th>#</th> 
       <th>Username</th> 
       <th>Ratio</th> 
       <th>Wins</th> 
       <th>Losses</th> 
       </thead> 

       <% @users.each do |user|%> 
       <tbody> 

       <td> 
       1 

       </td> 

       <td> 
        <%= user.username %> 
       </td> 

        <% if (Game.where(:winner_id => user.id).count) == 0 %> 

        <td>Unvalid</td> 

       <% elsif (Game.where(:loser_id => user.id).count) == 0 %> 

        <td>Unvalid</td> 

        <% else %> 
         <% @ratio = (number_with_precision((((Game.where(:winner_id => user.id).count).to_f)/(Game.where(:loser_id => user.id).count).to_f), precision: 2)) %> 

        <td><%= @ratio %></td> 


        <% end %> 

       <td> 
       <%= Game.where(:winner_id => user.id).count %> 
       </td> 
       <td> 
        <%= Game.where(:loser_id => user.id).count %> 
       </td> 


        <% end %> 
       </tbody> 
      </table> 

     </div> 

。リストは比率で並べる必要があります。 =>ビューからの@ratioこれを直接行うことはできますか?

最初のtdには、現在の位置が表示されます。すべてのユーザーに対して1と表示されます。どうすればいいですか?123、...?

答えて

4

Userモデルにこれらのメソッドを追加する必要があります。その後、コントローラで

class User < ActiveRecord::Base 
    has_many :wins, class_name: 'Game', foreign_key: 'winner_id' 
    has_many :losses, class_name: 'Game', foreign_key: 'loser_id' 

    def ratio 
    wins.count/losses.count.to_f * 100 
    end 
end 

def index 
    @users = User.all.sort_by(&:ratio) 
end 

とビューの

は、直接ユーザーインスタンスのメソッドを使用します。あなたはそれを@ThomasHaratykは上記提案した方法でやるべき <%= user.wins.count %>

1

その他の質問:最初の時点で現在の位置が表示されていますが、現在はすべてのユーザーに1が表示されていますが、どのようにすれば1、2、3、...?

<% @users.each_with_index do |user, index|%> 
    <tbody> 
     <td> 
      <%= index + 1 %> 
     </td> 
<% end %> 
関連する問題