[英]rails undefined method when iterating of array of methods
我是Rails初學者,正在嘗試在模型中添加一些代碼。 下面的代碼是一個說明。
視圖:
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”。 任何意見是極大的贊賞。
ruby中的注釋使用#
字符,而不是//
擺脫“ self.cmethod”,而僅使用“ cmethod”
if cmethod.find_with_passes....
在塊的范圍內,“ cmethod”只是局部變量。 通過將self放在它前面,ruby假定您正在對包含的類實例調用一個方法。
您的代碼正在調用self.cmethod
,它將嘗試在您的對象(不存在)上調用cmethod
方法。
我相信您要執行的操作類似於以下內容:
hands = [:lefthandstats, :righthandstats]
hands.each do |cmethod|
self.send(cmethod).... #rest of your code goes here
end
這將動態調用對象上的lefthandstats
和righthandstats
方法。
首先通過更換糾正代碼//
通過#
在我們使用的軌道#
由akofink提到的注釋代碼。
然后在您的代碼上下文中考慮這一點:
@result = Player.all
@result.each do |player|
player.name
end
@result
在這里返回玩家的集合。 因此,您可以對@result.each
使用循環,這樣對於作為玩家的每個結果,您將獲得每個玩家的名稱。
了解以上內容后,更正您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.