Rails 属于关联,当集合的一部分时无法访问所有者的属性?
我有一个物体,球,它属于一个女孩,它可以有很多球。大多数情况下一切正常,但如果我尝试通过以下方式打印出女孩的名字:
@balls.each do |b|
b.girl.name
end
我收到以下错误:
"undefined method `name' for nil:NilClass"
这真的让我很困惑。如果我说 b.girl.class,我会把它作为 Girl 的一个实例,很好。也就是说,它不是“NillClass”。
不仅如此,如果我对任何球尝试一下,并说
@ball.girl.name
我完全没问题。
到底是什么让我搞砸了《球》的收藏呢?
编辑:
具体来说,在我看来这正在发生。我现在正在进行测试,看看它是否也发生在控制器中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有一个
Ball
实例,但没有关联的Girl
。在访问girl
的name
属性之前,您需要检查以确保girl
不为nil
。You have an instance of
Ball
which does not have an associatedGirl
. You'll want to check to make sure thatgirl
isn'tnil
prior to accessing hername
attribute.丹吉特,好吧,没关系。问题是,由于某种原因,某些球对象实际上没有女孩(尽管大多数都有,所以我尝试的任何给定球都工作得很好,但如果我尝试做所有这些,其中一个会失败,并且视图错误只让我知道出了问题,而不是哪里出了问题)
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)