2009-10-21 78 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和空字符串