3

我有以下类在我的单元测试中运行良好,但我觉得它可能更简单。

class License < ActiveRecord::Base
  scope :active, lambda {
    where("active_from <= ?", Date.today).order("version_number DESC")
  }
end

def current_license
  return License.active.first
end

public :current_license

我尝试将 附加.firstlambda子句中,但这会导致错误。

我如何告诉scope我只想要第一个结果,从而current_license完全消除该方法?

4

1 回答 1

2

让它成为一种方法,你可以得到这个:

class License < ActiveRecord::Base

  def self.current_license
    return License.where("active_from <= ?", Date.today).order("version_number DESC").first
  end

end

至于结果的数量,尝试添加一个.limit(1). 有关更多信息,请查看此处

于 2011-09-27T10:13:19.547 回答