How come this works and doesn't work in IRB?
-
29-09-2019 - |
Question
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.
Solution
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}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow