Search code examples
ruby-on-railsrubybelongs-to

Rails belongs_to association, can't access owner's attributes when part of a collection?


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.


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