开发者

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

开发者 https://www.devze.com 2023-01-11 19:02 出处:网络
I have Users . Users have_many :organizations If I do: User.find(:all).select {|u| u.organizations.first.name 开发者_如何学运维}

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

精彩评论

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