2011-09-27 51 views
3

我有以下类在单元测试中正常工作,但我觉得它可能更简单。使用ActiveRecord的范围指令返回单个结果

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

回答

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)。欲了解更多信息,看看here

+0

:-)良好的作品,更简单。一个问题是,那里需要的“自我”,还是只是一种风格的东西? –

+0

自我需要,因为这是一种班级方法。 – Geo

+0

真的吗?我以前没见过。 –