为什么这样有效并且在IRB中不起作用?

Tri*_*rip 1 ruby ruby-on-rails irb

我有用户.用户has_many:组织

如果我做:

User.find(:all).select {|u| u.organizations.first.name }
Run Code Online (Sandbox Code Playgroud)

它返回:

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
Run Code Online (Sandbox Code Playgroud)

长话短说:

我试图找到每个用户的第一个组织的名称.

Ste*_*eet 8

因为你的一个用户没有任何组织所以organization.first是零

你可以这样做来防止这种情况

User.find(:all).select {|u| 
  u.organizations.first.name unless u.organizations.size == 0}
Run Code Online (Sandbox Code Playgroud)