2010-08-17 38 views
1

我有用戶。用戶have_many:組織這是如何工作的,在IRB中不起作用?

如果我做的:

User.find(:all).select {|u| u.organizations.first.name } 

它返回:

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 

長話短說:

我試圖從找到的第一個組織的名稱每個用戶。

回答

8

因爲你的用戶沒有任何組織這樣organizations.first爲零

可以防止這種做

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