2013-08-28 34 views
1

我不知道什麼美麗的方式來輸出這在Rails中。Rails複雜如果

order.items.min.user.email 

我想告訴電子郵件的價值,我唯一知道的是爲了不是零,但項目用戶可能是零。

我看到的唯一方法是

if !order.items.empty? 
    if !order.items.min.user.nil? 
    if !order.items.min.user.email.nil? 
     order.items.min.user.email 
    end 
    end 
end 

看起來不是最好的方式,你知道更好的辦法?

回答

14

你可以使用try(或try!取決於您Rails3中的版本,以及如何你想處理未知的方法):

order.items.try(:min).try(:user).try(:email) 

try是吞下nil S(並根據知曉的方法可以輕鬆地提高Rails版本)在一個長的方法調用鏈中。

+0

太神奇了,謝謝! – user10756

+0

呼叫鏈太長,考慮我的回答低於 –

+0

@mu ...你真棒 –

7

考慮這個更好的方法:

訂單:

class Order < ActiveRecord::Base 
    has_many :items 
end 

項目:

class Item < ActiveRecord::Base 
    belongs_to :user 

    delegate :email, to: :user, allow_nil: true, prefix: true # You can remove the prefix true and call item.email instead item.user_email 
end 

然後:

order.items.min.try(:user_email) 

或:

order.items.min.try(:user_email).presence || "Not found" 

如果items.min爲零,用戶爲零,或電子郵件爲零,將返回用戶的電子郵件或「未找到」。

+0

這是因爲它沒有意義屬於用戶的訂單項:)。這是德米特的法律應用。 –

+0

此外,該行可用於應用程序的其他部分,這確實會降低總體複雜性。 –