0

这让我很困扰。它看起来不太干。什么是更好的实施方式?顺便说一句,为什么这个 ActiveRecord 查找器在找不到记录时不抛出异常,但是 .find 呢?

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

4 回答 4

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

如果没有找到记录,动态find_by方法返回 nil,find_by_all返回一个空数组。

于 2009-10-21T17:00:34.373 回答
3

我会这样编码

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

至于异常,find_by 动态方法返回nil而不是抛出异常。如果你想要一个例外,使用findwith :conditions

def current_account
  @account ||= current_subdomain.blank? ? nil : Account.find(:first, :conditions => {:host  => current_subdomain})
end
于 2009-10-21T17:05:54.357 回答
0

怎么样:

def current_account
  @account ||= Account.find_by_host(current_subdomain) unless current_subdomain.blank?
end
于 2009-10-21T16:59:58.317 回答
0
def current_account  
  @account ||= current_subdomain.present? && Account.find_by_host(current_subdomain)
end

#present?将处理nil并清空字符串

于 2014-01-11T21:07:36.940 回答