-1

I have a rails model (Comment) which is based on neo4j.rb. My simple method should return the number of children, but is instead returning a LocalJumpError (no block given (yield)). What am I doing wrong?

has_many :both, :children, model_class: Comment, unique: true

def get_number_of_replies
    if children.count == 0
      0
    else
      children.count + children.each.get_number_of_replies
    end
end
Joe Eifert
  • 1,306
  • 14
  • 29
  • I suspect you need some parentheses. See http://stackoverflow.com/questions/18623447/block-syntax-difference-causes-localjumperror-no-block-given-yield – Robert Harvey Feb 23 '15 at 18:35

3 Answers3

1

I think

children.count + children.each.get_number_of_replies

should be

children.count + children.collect(&:get_number_of_replies).sum

As your error indicates, each expects a block.

Brad Werth
  • 17,411
  • 10
  • 63
  • 88
  • This returns a SystemStackError(stack level too deep), but is definitely the right way to go. EDIT: I have only one nested comment, so the error can not be that I have too many comments. – Joe Eifert Feb 23 '15 at 18:44
  • And children.children.count returns 0 – Joe Eifert Feb 23 '15 at 18:46
1

You need to loop through every children to get the result you want:

def get_number_of_replies
  if children.count == 0
    0
  else
    total = 0
    children.each do |c|
      total += children.get_number_of_replies
    end
    children.count + total
  end
end
hbejgel
  • 4,674
  • 2
  • 17
  • 27
0

What Brad Werth wrote is correct. The problem was also that as children connections work both ways, I was creating an infinite loop. So here is the solution:

  has_many :out, :children, model_class: Comment, unique: true
  has_one :in, :child_of, model_class: Comment, unique: true

  def get_number_of_replies
    result = 0
    unless children.count() == 0
      result += children.count
      children.each do |child|
        result += child.get_number_of_replies
      end
    end
    result
  end
Joe Eifert
  • 1,306
  • 14
  • 29