[英]Rails (postgres) query with jsonb array
我的產品模型有一個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']) }
ActiveRecord等價物(如果spec_option
是常規列):
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
有人有想法嗎?
你想要使用的是@>
運算符 ,它測試你的左手值是否包含右手值。 “包含”適用於對象和數組,因此以下查詢將起作用:
SELECT * FROM products WHERE specs->'spec_options' @> '["spec1", "spec2"]';
我相信你可以轉換成ActiveRecord兼容的語法,如下所示:
scope :with_spec_options, ->(spec_options) {
where("specs->'spec_option' @> ?", spec_options.to_json)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.