开发者

How come this works and doesn't work in IRB?

I have Users . Users have_many :organizations

If I do:

User.find(:all).select {|u| u.organizations.first.name 开发者_如何学运维}

it returns with:

NoMethodError: You have a nil object when you didn't expect it!
The error occurred while evaluating nil.name
from (irb):33
from (irb):33:in `select'
from (irb):33

Long story short:

I am trying to find the names of the first organization from each user.


Because one of your users does not have any organizations so organizations.first is nil

You can prevent this by doing

User.find(:all).select {|u| 
  u.organizations.first.name unless u.organizations.size == 0}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜