如何在 rails 的数组中查询带有哈希的 json 数据?

How to query json data with hashes inside array in rails?

我在Note机型上有如下一组数据。目前,我正在为数据库使用 Postgres。以下是 Notes table.

上的两条不同记录
id: 1,
name: 'First Note',
items: [{description: 'First Note'}, {description: 'PM1 Second Note'}]

id: 2,
name: 'Second Note',
items: [{description: 'Second Note'}, {description: 'PM2 Second Note'}]

id: 3,
name: 'Third Note',
items: [{description: 'Third Note'}, {description: 'Invalid Second Note'}]

如何查询 json 字段(项目),以便在描述字段中获取所有值为 PM 的注释,即查询应该 return 带有 id 1 的注释和上面例子中的 2?

我没有测试,但以下其中一项应该有效。

Note.where("items->>'description' iLIKE ?", '%PM%')
# or
Note.where("items::json -> 'description' iLIKE ?", '%PM%')

使用原始 SQL 您可以通过以下方式实现:

select * from notes,
  json_array_elements(items) element
  where element->>'description' LIKE '%PM%';

使用 activerecord 尝试以下操作:

Note.where("EXISTS (SELECT FROM json_array_elements(items) element WHERE element->>'description' LIKE '%PM%')")