Rails is an association, can't access owner attributes on partial collection?

I have an Object, Ball, which belongs to Girl, which can have many balls. Everything works for the most part, but if I try to print the name of the girl through:

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

I get the following error:

"undefined method `name' for nil:NilClass"

What really bothers me. If I say b.girl.class, I get it as an instance of Girl, just fine. That is, it is not a "NillClass".

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

@ball.girl.name

I'm fine.

What happens to the collection of balls that wrap me?

Edit:

In particular, this is happening in my opinion. I am testing now to see if this is happening in the controller.

+3
2

Ball, Girl. , Girl nil name.

@balls.each do |b|
  b.girl.name unless b.girl.nil? 
end
+5

, , . , - - Ball ( , Ball, , , , , , - , )

+1

Source: https://habr.com/ru/post/1736165/


All Articles