Chr*_*rke 3 ruby-on-rails default-scope ruby-on-rails-4 ruby-on-rails-5
我一直在寻找这个并且似乎无法找到答案,虽然我认为如果你对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) where(active: true) }
Run Code Online (Sandbox Code Playgroud)
我知道这可能只是一个我不理解的语法问题.如果有人能给我如何解决这个问题的建议,将不胜感激!谢谢!
我想你要做的就是这个
default_scope -> { where(active: true).order(created_at: :desc) }
Run Code Online (Sandbox Code Playgroud)
所以,你只是有一个语法问题.当他们将新的lambda范围语法添加到rails时,由于其功能性编程起源(给定rails是面向对象的语言),许多ruby开发人员对它有点不熟悉.有效地,代码段{}
就像块一样,并在内部执行代码.该where
子句在声明作用域的模型上被隐式调用.该where
子句返回一个ActiveRecord
关系对象(即数据库记录的集合),它实现了order
通过传递的属性对关系中的记录进行排序的方法(在此case created_at
)基于传入的参数的递降(desc
)或升序(asc
)顺序.
归档时间: |
|
查看次数: |
1765 次 |
最近记录: |