【问题标题】:Correctly using Scope in rails 4 model在 rails 4 模型中正确使用 Scope
【发布时间】:2014-09-08 11:44:18
【问题描述】:

我正在使用范围来获取随机横幅,我正在使用 gem Randumb

scope :sidebar_top, -> { where(ad_type_id: 2).order_by_rand.first }

如果没有找到广告,则返回所有行。根据 Randumb 文档,它应该在没有找到任何东西的情况下返回 nil。

我应该首先使用范围返回单个实例吗?这似乎是最好的方法,但我很少看到范围示例返回的子集少于一小部分。

如果什么也没找到,我有什么办法可以返回 nil 吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord scope


    【解决方案1】:

    这样的?类方法而不是作用域。

    def self.sidebar_top
      where(ad_type_id: 2).blank? ? nil : where(ad_type_id: 2).order_by_rand.first
    end
    

    【讨论】:

    • 非常感谢!这也使我能够在将来扩展它。
    【解决方案2】:

    您不应该使用范围来返回单个实例。观察 [1]

    至于答案:

    def self.sidebar_top
      Array(where(ad_type_id: 2).order_by_rand).first # single query
    end
    

    [1] 作用域需要一个作用域返回:如果 proc 返回 nil 或 false,则返回一个作用域。

    scope :this_or_all, ->(feeling) { where(state: feeling) if feeling.present? }
    

    因此,您可以这样做User.this_or_all(nil).this_or_all(happy)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      相关资源
      最近更新 更多