JSONB哈希的Rails作用域,值为数组



我使用的是一个JSONB列,其中数据存储为{key=>[value,value,value]}如何编写一个范围来返回在特定键的数组中包含特定值的记录?

我已经学会了如何搜索简单的JSON哈希;

scope :rice_flour, -> { where("ingredients ->> 'flour' = ?", "rice") }

但我仍然无法理解这种查询类型。我所查找的所有内容都在原始SQL命令中列出,我正在寻找如何编写整洁的Rails Scopes。

使用@>运算符:

postgres@/> select '["a", "b"]'::jsonb @> '["a"]';
+------------+
| ?column?   |
|------------|
| True       |
+------------+
postgres@/> select '["a", "b"]'::jsonb @> '["c"]';
+------------+
| ?column?   |
|------------|
| False      |
+------------+

https://www.postgresql.org/docs/10/functions-json.html

您的范围如下:

scope :rice_flour, -> { 
.where("ingredients -> 'flour' @> '["rice"]'::jsonb")
}

这将生成类似SQL的:

WHERE (ingredients -> 'flour' @> '["rice"]'::jsonb)

假设flour是关键字,rice是数组中的值之一。

最新更新