【问题标题】:How to add multiple conditions to Rails scope?如何向 Rails 范围添加多个条件?
【发布时间】:2016-10-19 20:35:39
【问题描述】:

我一直在寻找这个问题,但似乎无法找到答案,尽管我认为如果您对 Rails 的经验比我更有经验,这应该是一个很容易解决的问题。我正在尝试将多个 default_scope 条件添加到我的 Product 模型中。我的产品型号文件如下:

class Product < ApplicationRecord
    has_many :order_items
    default_scope { where(active: true) }
    validates :name,  presence: true, length: { maximum: 300 }
    PRICE_REGEXP = /\A\d{1,4}(\.\d{0,2})?\z/
    validates :price, presence: true,
                      numericality: true,
                      format: { with: PRICE_REGEXP }
    validates :description, presence: true, length: { maximum: 1000 }, 
                            allow_nil: true
end

我也想补充一下

default_scope -> { order(created_at: desc) }

使产品索引页面上的新产品采用最新优先的格式。每当我执行以下操作时都会收到语法错误消息:

default_scope -> { order(created_at: desc) }, { where(active: true) }

default_scope -> { order(created_at: desc), where(active: true) }

default_scope -> { order(created_at: desc) where(active: true) }

我知道这可能只是我不理解的语法问题。如果有人可以就如何解决这个问题给我建议,将不胜感激!谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 default-scope


    【解决方案1】:

    我认为你想要做的是这个

    default_scope -> { where(active: true).order(created_at: :desc)  }
    

    实际上,您只是遇到了语法问题。当他们将新的lambda 范围语法添加到 rails 时,由于它的函数式编程起源(鉴于 rails 是面向对象的语言),许多 ruby​​ 开发人员对它有点陌生。实际上{} 中的代码段就像一个块并执行里面的代码。 where 子句在声明范围的模型上被隐式调用。where 子句返回一个 ActiveRecord 关系对象(即数据库记录的集合),它实现了对记录进行排序的 order 方法根据传入的参数,以降序 (desc) 或升序 (asc) 传递的属性(在本例中为 created_at)在关系中。

    【讨论】:

    • 如果您描述它为什么起作用,这将是一个更好的答案。
    • 通过链接方法调用来编写活动记录中的范围就足够了。
    • 哦,我想这个解释有点过头了,但我很高兴你把你的评论包括在内。
    • 谢谢你!解决了我的问题。解释也很有帮助!
    • @CdotStrifeVII 如果我必须对 Order 有一个“或”条件怎么办,比如说我想在名称上订购(如果存在),否则订购时创建在。我如何做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2014-10-11
    • 2015-02-14
    • 2015-11-05
    • 2017-06-25
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多