gpt4 book ai didi

ruby - 使用 ActiveRecord 的 scope 指令返回单个结果

转载 作者:数据小太阳 更新时间:2023-10-29 08:05:50 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

把它做成一个方法,你可以得到这个:

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 .

关于ruby - 使用 ActiveRecord 的 scope 指令返回单个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7567327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com