gpt4 book ai didi

ruby-on-rails - 如何向 Rails 范围添加多个条件?

转载 作者:行者123 更新时间:2023-12-01 09:49:48 25 4
gpt4 key购买 nike

我一直在寻找这个问题,但似乎找不到答案,尽管我认为如果您对 Rails 的经验比我丰富,那么这应该是一个非常容易解决的问题。我正在尝试向我的产品模型添加多个 default_scope 条件。我的产品模型文件如下:

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) }

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

最佳答案

我认为你正在尝试做的是这个

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

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

关于ruby-on-rails - 如何向 Rails 范围添加多个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40141059/

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