无法在模型方法中调用子方法

时间:2013-08-28 08:56:12

标签: ruby-on-rails methods each

我正在努力解决这个问题:

在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>

如果我在视图中放置相同的每个块,它会按预期工作(我可以在每个块中调用'goal'上的方法)

2 个答案:

答案 0 :(得分:1)

它做了一些事情 - 它返回数组self.goals这是正确的行为。您要做的是使用map代替each

答案 1 :(得分: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