2010-07-19 29 views
0

我有一個用戶模型和一個出價模型。我希望用戶根據作爲方法存儲的分數知道他們的等級是什麼,即基於方法的「3/7」。目前,我試圖妥善保存該geek_rank方法爲Bid模型:爲什麼我不能在模型中使用sort_by?

def user_rank(my_id) 
    #Finds all bids associated with parent ticket object 
    bids = Bid.find_by_ticket_id(self.ticket.id) 
    bids = bids.sort_by { |b| b.user.score} 
    i = 0 
    for b in bids 
    i += 1 
    if b.user_id.to_i == my_id.to_i 
     myrank = i 
    end 
    end 
    user_rank = myrank.to_s + "/" + i.to_s 
end 

出於某種原因,sort_by方法工作的控制器,但不是當我嘗試在模型中進行排序。任何人都可以告訴我這個問題是如何與我的代碼如何吸? :)

澄清:

實際的錯誤,我得到的是一個方法,缺少錯誤。

回答

4

方法find_by_ticket_id不返回數組;它返回一個投標。 改爲使用find_all_by_ticket_id

bids = Bid.find_all_by_ticket_id(self.ticket.id) 
bids = bids.sort_by { |b| b.user.score} 

如下我會重寫你的方法:

def user_rank(my_id) 
    # find the bid by the given id 
    score = Bid.find_by_id(my_id).user.score 

    # find the total number of bids for the ticket 
    count = Bid.count(:conditions => {:ticket_id => self.ticket.id}) 

    # find the rank 
    rank = Bid.count(:conditions => ["ticket_id =? AND users.score > ? ", 
       self.ticket.id, score], :joins => :user) + 1 
    "#{rank}/#{count}" 
end 

在這種方法中大部分的計算是由數據庫完成的。

買者1

此方法將返回同級別的人同分。

E.g:

#name #score #rank 
foo  5  4 
bar  6  2 
kate  6  2 
kevin  8  1 

買者2

該解決方案的性能比你的更好的解決方案。但它仍然需要n * 3次往返服務器來計算排名。解決方案可以進一步優化,以計算一個SQL中所有用戶的排名。

相關文章排名計算的優化:

Article 1

+0

Find_all_by_ticket_id應該是票據。 +1回答這個問題 – 2010-07-20 03:21:22

+0

非常感謝Kandada! – Kevin 2010-07-21 17:46:32

0

所以,是從方法返回的分數爲有理數,例如3/7或者他們是Fixnums?

ruby-1.8.7-p299 > require 'mathn' 
=> true 
ruby-1.8.7-p299 > Rational 
=> Rational 
ruby-1.8.7-p299 > Rational(3/7) 
=> 3/7 
ruby-1.8.7-p299 > Rational(3/7) <=> Rational(5/7) 
=> -1 

,但如果它們被評價爲fixnums然後3/7返回零,和Ruby斜面比較0到:

如果它們是有理數則它們應該能夠通過enumarable sort_by方法進行比較0(整數除法)

ruby-1.8.7-p299 > 3/7 
=> 0 
ruby-1.8.7-p299 > 5/7 
=> 0 
ruby-1.8.7-p299 > 3/7 <=> 5/7 
=> 0 
ruby-1.8.7-p299 > 5/7 <=> 5/7 
=> 0 
ruby-1.8.7-p299 > 8/7 <=> 5/7 
=> 1 
ruby-1.8.7-p299 > 7/7 <=> 7/7 
=> 0 
+0

我得到一個方法缺少錯誤說沒有這樣的事情sort_by – Kevin 2010-07-20 00:43:16

+0

如果你得到一個無方法錯誤,那麼什麼是從您的出價分配回來不是實現枚舉的數據結構。您可以在出價排序調用之前添加跟蹤聲明,(STDERR.puts bids.inpsect) – 2010-07-20 01:47:40

相關問題