2016-04-04 40 views
1

我試圖存儲國際足聯比賽,並設置了排名系統的記分牌。按循環中的值排序

我不應該在視圖中使用邏輯,但是如果我在控制器中計算它們,它會呈現未指定方法用戶的錯誤。然而,當我將它放入循環中時,它會識別它,因爲用戶是循環項目。

該應用程序可以保存遊戲並計算贏家。該應用程序將winner_idloser_id添加到每個遊戲。在記分牌後面,我計算循環中有多少個當前的user_id匹配所有遊戲的winner_idloser_id。這可以保持數據庫的清潔。我不想在數據庫中保持勝負,因爲當一場比賽被刪除時,它不應該算作贏或輸。

控制器:

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。我怎樣才能使這1,2,3,...?

回答

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 

,並在視圖中,直接使用用戶實例方法: <%= user.wins.count %>

1

你應該做@ThomasHaratyk已經上文建議的方式。

附加問題:在第一個td中顯示當前位置,現在它爲每個用戶顯示一個1,我怎樣才能使這個1,2,3 ......?

<% @users.each_with_index do |user, index|%> 
    <tbody> 
     <td> 
      <%= index + 1 %> 
     </td> 
<% end %>