我一直在寻找这个并且似乎无法找到答案,虽然我认为如果你对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
Run Code Online (Sandbox Code Playgroud)
我想补充一点
default_scope -> { order(created_at: desc) }
Run Code Online (Sandbox Code Playgroud)
所以产品索引页面上的新产品的格式是最新的.我在任何时候执行以下操作时都会收到语法错误消息:
default_scope -> { order(created_at: desc) }, { where(active: true) }
Run Code Online (Sandbox Code Playgroud)
要么
default_scope -> { order(created_at: desc), where(active: true) }
Run Code Online (Sandbox Code Playgroud)
要么
default_scope -> { order(created_at: desc) …Run Code Online (Sandbox Code Playgroud)