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>

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

4

2 回答 2

1

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

于 2013-08-28T08:58:19.497 回答
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
于 2013-08-28T08:59:06.933 回答