检查ActiveRecord查询中的nil结果

jhw*_*ist 1 activerecord ruby-on-rails

我在模型中有一些地方可以做类似的事情

  def ServerInfo.starttime(param)
    find(:all, :conditions => "name ='#{param}_started'", :select => "date").first.date.to_datetime
  end
Run Code Online (Sandbox Code Playgroud)

现在,由于与问题无关的原因,可能会发生这个特定行根本不在数据库中,并且上面的代码失败了NoMethodError (undefined method `date' for nil:NilClass):.我目前的解决方案是

    res = find(:all, :conditions => "name ='#{param}_started'", :select => "date")
    check_time = res.first.nil? ? 0 : res.first.date.to_datetime
Run Code Online (Sandbox Code Playgroud)

这可以找到,但我觉得在整个地方撒上代码是不对的.是否有更多的ruby-ish/rail-ish方法来防止解除引用nil?

jpe*_*thy 6

为了避免Noil的NoMethodError,你应该定义一个begin rescue块,

def ServerInfo.starttime(param)
  begin
    find(:all, :conditions => "foo").first.date.to_datetime
  rescue
    0
  end
end
Run Code Online (Sandbox Code Playgroud)

我也喜欢Rails的try方法:

find(:all, :conditions => "foo").first.try(:date).try(:to_datetime) || 0
Run Code Online (Sandbox Code Playgroud)