2013-08-28 168 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