我的产品模型有一个jsonb字段specs
(我们使用ActiveRecord的store_accessor
进行管理)。我的许多产品规格在哈希表中都有一个叫做spec_options
的规格。
到现在为止,这个spec_option
字段只是文本。现在它需要成为一个数组。
以前用于查询此字段产品的范围是:
scope :with_spec_options, ->(spec_options) {
where("'#{spec_options}'::jsonb \? (specs->>'spec_option')")
}
Ruby等价代码(只是为了帮助理解这段代码在做什么):
select{ |product| spec_options.include?(product.specs['spec_option']) }
如果 spec_option
是一个常规列,那么它的 ActiveRecord 等效代码如下:
where(spec_option: spec_options)
然而,现在specs['spec_options']
是一个数组,我无法这样做。我想我需要使用Postgres的?|
jsonb运算符,但我无法弄清楚如何将此操作的右侧转换为正确的格式。
Ruby等价代码:
def self.with_spec_options(spec_options)
all.select{|product|
if product.specs['spec_options'].present?
product.specs['spec_options'].any?{|option|
spec_options.include?(option)
}
else
false
end
}
end
有人有想法吗?
where("specs->'spec_option' @> ?::jsonb", spec_options.to_json)
- Obversitywhere("specs->'spec_option' @> ?", spec_options.to_json)
- Obversitywhere("specs->'spec_option' ?| :options", options: spec_options)
。 - Robert Nubelwhere("specs->'spec_option' ?| array[:options]", options: spec_options)
。将其插入正确的Postgres语法中有点棘手。 - Robert Nubel