2013-08-28 166 views
0

我有這個一個真正的鬥爭:無法調用模型方法,孩子的方法

在student.rb:

def subject_avg 
    self.goals.each do |goal| 
     goal.subject_id 
    end 
    end 

這不「做」什麼 - 或者我應該說它不會從

def subject_avg 
    self.goals.each do |goal| 
     goal.id 
    end 
    end 

def subject_avg 
    self.goals.each do |goal| 
     goal.goal 
    end 
    end 
做什麼不同

不管是什麼,它返回的目標數組屬於主題:

[ 
    #<Goal id: 28, goal: "Do it on command", subject_id: 10, created_at: "2013-08-25 10:59:35", updated_at: "2013-08-25 10:59:35", default: nil>, 
    #<Goal id: 29, goal: "Make it chunky", subject_id: 10, created_at: "2013-08-25 10:59:35", updated_at: "2013-08-25 10:59:35", default: nil>, 
    #<Goal id: 30, goal: "Hit the mark", subject_id: 10, created_at: "2013-08-25 10:59:35", updated_at: "2013-08-25 10:59:35", default: nil>, 
    #<Goal id: 31, goal: "Puke and rally", subject_id: 10, created_at: "2013-08-25 10:59:35", updated_at: "2013-08-25 10:59:35", default: nil> 
] 

起初我以爲它只是沒有讀/無法讀取出於某些原因,每塊所以只是路過self.goals.each的結果(雖然這似乎是發生了什麼)。然而,如果我所說的不存在的方法,它拋出一個錯誤:

def subject_avg 
    self.goals.each do |goal| 
     goal.FFS_do_something! 
    end 
    end 

回報

undefined method `FFS_do_something!' for #<Goal:0x000001064329f0> 

,如果我把同樣的視圖中的每個塊,它按預期工作(我可以打電話方法在每個塊內'目標')

回答

1

我認爲你需要map代替each

def subject_avg 
    self.goals.map do |goal| 
     goal.subject_id 
    end 
    end 

def subject_avg 
    self.goals.map(&:subject_id) 
    end 
1

它做了一些事情 - 它返回數組self.goals這是正確的行爲。你想要做的是使用map而不是each