views:

219

answers:

2

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.

A: 

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
Aaron Hinni
Oooo, I didn't know unless could be used that way. That's much more efficient than the if statements I was using.
Jenny
A: 

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)

Jenny