3

I have an Object, Ball, which belongs_to a Girl, which can have_many balls. Everything works for the most part, but if I try to print out the girls' name via:

@balls.each do |b|
    b.girl.name
end

I get the following error:

"undefined method `name' for nil:NilClass"

Which really confuses me. If I say b.girl.class, I get it as an instance of Girl, just fine. That is, it isn't "NillClass".

Not only that, if I just try it for any Ball, and say

@ball.girl.name

I'm perfectly fine.

What is it about a collection of Balls that is screwing me up?

Edit:

Specifically this is happening in my view. I'm doing testing now to see if it happens in the controller, too.

0

2 Answers 2

5

You have an instance of Ball which does not have an associated Girl. You'll want to check to make sure that girl isn't nil prior to accessing her name attribute.

@balls.each do |b|
  b.girl.name unless b.girl.nil? 
end
1
  • Oooo, I didn't know unless could be used that way. That's much more efficient than the if statements I was using.
    – J.R.
    Mar 11, 2010 at 12:39
1

Dangit, okay, never mind. The issue was that for some reason some Ball Object didn't actually have girls (though most did, so any given Ball I tried worked fine, but if I tried to do all of them, one of them would fail, and the view error only let me know that something went wrong, not where)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.