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

这一生的挚爱 提交于 2019-12-07 17:54:01

问题


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.


回答1:


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



回答2:


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)



来源:https://stackoverflow.com/questions/2411040/rails-belongs-to-association-cant-access-owners-attributes-when-part-of-a-col

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!