简体   繁体   中英

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM