Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top