本文介绍了Railsbelongs_to 关联,作为集合的一部分无法访问所有者的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个物体,球,它属于一个女孩,它可以有_许多球.大部分情况下一切正常,但如果我尝试通过以下方式打印女孩的名字:

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

我收到以下错误:

"undefined method `name' for nil:NilClass"

这让我很困惑.如果我说 b.girl.class,我把它当作 Girl 的一个实例,就好了.也就是说,它不是NillClass".

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

我很好.

是什么让我搞砸了球的集合?

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

特别是在我看来这是正在发生的.我现在正在做测试,看看它是否也发生在控制器中.

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

推荐答案

您有一个 Ball 的实例,它没有关联的 Girl.在访问她的 name 属性之前,您需要检查以确保 girl 不是 nil.

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

这篇关于Railsbelongs_to 关联,作为集合的一部分无法访问所有者的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 16:31