【问题标题】:Using ActiveRecord's scope instruction to return a single result使用 ActiveRecord 的作用域指令返回单个结果
【发布时间】:2011-09-27 10:01:03
【问题描述】:

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

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

【问题讨论】:

    标签: ruby activerecord scope simplification


    【解决方案1】:

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

    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

    【讨论】:

    • :-) 是的,它有效且更简单。一个问题,那里需要self. 还是只是一种风格?
    • 需要self,因为这是一个类方法。
    • 真的吗?我以前没见过。
    • 然而,更一般地说,实际上有什么方法可以让作用域查询返回单个结果?
    • @Dave Sag,请立即使用.limit 方法检查。
    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多