2

给定一个包含零个或一个元素的数组,我如何返回第一个元素或零?

我有工作代码,但它不是很优雅:

class Category < ActiveRecord::Model
  adapter sqlite

  table_name "categories"

  primary id      : Int
  field parent_id : Int
  field name      : String

  # return a category or nil
  def self.root
    roots = where(criteria("parent_id").is_null)

    if roots.empty?
      nil
    else
      roots.first
    end⋅
  end
end
4

1 回答 1

3

您可以简单地调用first?数组:

  def self.root
    where(criteria("parent_id").is_null).first?
  end
于 2016-04-06T16:57:04.160 回答