2013-02-27 75 views
0

我是一名rails初學者,並試圖在模型中添加一些代碼。下面的代碼是一個例子。rails迭代方法數組undefined方法

查看:

Player_stats: <%= @player.player_pass_completion_ratio %> 

型號:

class Player < ActiveRecord::Base 
has_many :lefthandstats 
has_many :righthandstats 

def player_pass_completion_ratio 
Hands = [ lefthandstats, righthandstats] #These are objects & calling @player.lefthandstats.find_with_passes directly generally works 

if self.category == "Hands" 
    total_usual_passes = 500 
    Hands.each do |cmethod| 
    if self.cmethod.find_with_passes(:passes, :first, {:conditions => 'passes>200' }) then accuratestats += 1 end 
    end 
end 

accuracy = (accuratestats/total_usual_passes)*100 
end 

我得到一個未定義的方法 「cmethod」 當我嘗試調用視圖中的代碼。任何意見是極大的讚賞。

+0

在該方法的第一行,這似乎是說,你要在一個名爲Hands的數組中放置兩個局部變量名稱'lefthandstats'和'righthandstats'。但是,由於這是該方法的第一行,因此這兩個變量尚未定義,因此它們爲零。 – GSP 2013-02-27 14:19:34

回答

1

您的代碼調用self.cmethod,它會嘗試打電話給你的對象上cmethod方法(不存在)。

我相信你正在試圖做的是類似如下:

hands = [:lefthandstats, :righthandstats] 
hands.each do |cmethod| 
    self.send(cmethod).... #rest of your code goes here 
end 

這將動態調用的對象上lefthandstatsrighthandstats方法。

+0

感謝您的輸入! – 2013-02-27 16:04:55

1

擺脫「self.cmethod」的,只是用「cmethod」

if cmethod.find_with_passes.... 

在塊「cmethod」的範圍僅僅是一個局部變量。通過把自己放在它前面,ruby假定你正在調用包含類實例的方法。

+0

感謝您的輸入。我把它取下來,現在得到'未定義的方法'/'爲零:NilClass'。按照我實施的方式在塊中傳遞方法是否可行? – 2013-02-27 14:12:14

+0

我看的越多,所寫的代碼就無法工作。你在一個名爲'Hands'的數組中有兩個'somethings'。爲了完成這項工作,你調用'find_with_passes'的'東西'必須定義該方法。你說'lefthandstat'是一個對象。什麼類型的對象? – GSP 2013-02-27 14:16:28

+0

順便說一下,'undedeinfed方法nil:NilClass'是因爲「Hands」數組中的對象爲零。 – GSP 2013-02-27 14:17:53

2

評論紅寶石使用#字符,而不是//

+0

雖然這是真的,但它不回答問題。 – sevenseacat 2013-02-27 14:11:51

0

首先通過將//替換爲#來更正您的代碼,如在rails中我們使用#來評論akofink所述的代碼。

然後考慮這在你的代碼的情況下:

@result = Player.all 

@result.each do |player| 

player.name 

end 

這裏@result正在恢復的球員的集合。所以你可以使用@result.each這樣的循環,這樣對於每個玩家的結果,你都會得到每個玩家的名字。

用上面的知識修正你的代碼。