2009-10-21 77 views
0

這是困擾我。它看起來不太乾。什麼是更好的實施?順便說一句,當沒有找到記錄時,這個ActiveRecord finder怎麼會不會引發異常,但是.find呢?如何幹這段Ruby代碼?

def current_account 
    return @account if @account 
    unless current_subdomain.blank? 
     @account = Account.find_by_host(current_subdomain) 
    else 
     @account = nil 
    end 
    @account 
    end 

回答

3

我想

def current_account 
    @account ||= current_subdomain.blank? ? nil : Account.find_by_host(current_subdomain) 
end 

至於異常的代碼本,find_by動態方法返回nil,而不是拋出異常。如果你想要一個例外,使用find:conditions

def current_account 
    @account ||= current_subdomain.blank? ? nil : Account.find(:first, :conditions => {:host => current_subdomain}) 
end 
0

如何:

def current_account 
    @account ||= Account.find_by_host(current_subdomain) unless current_subdomain.blank? 
end 
5
def current_account 
    @account ||= current_subdomain && Account.find_by_host(current_subdomain) 
end 

如果找不到記錄,動態find_by方法返回nil,find_by_all返回一個空數組。

+0

+1,你比我好多了。 – 2009-10-21 17:05:09

+0

但是,如果current_subdomain是空字符串,則不應調用.find_by_host。 如果&&失敗,將分配什麼@account?假? – Alexandre 2009-10-21 17:41:38

+1

但是,如果current_subdomain是「」,則會失敗。 「」在布爾上下文中評估爲true。應該是'!current_subdomain.blank?' – EmFi 2009-10-21 20:37:57

0
def current_account 
    @account ||= current_subdomain.present? && Account.find_by_host(current_subdomain) 
end 

#present?將處理nil和空字符串