简体   繁体   中英

Unable to call child methods in model method

I'm having a real struggle with this:

In student.rb:

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

This doesn't 'do' anything - or I should say it doesn't do anything different from

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

or

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

no matter what, it returns an array of goals that belong to the subject:

[
  #<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>
] 

at first I thought it just wasn't reading/couldn't read the each block for some reason so was just passing the result of self.goals.each (although that does seem to be what's happening). However, if i call a non-existent method, it throws an error:

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

returns

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

if I put the same each block in the view, it works as expected (I can call methods on 'goal' within the each block)

It does something - it returns the array self.goals which is correct behaviour. What you wanted to do is to use map instead of each .

I think you need map instead of each

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM