我正在使用 Postgres 的 JSON 数据类型来存储一些信息。
例如,我有一个模型 User
,它有一个字段 locations
,它包含一个 json 文档(包含键和值对的对象数组),格式如下:
[{"name": "Location 1", kind: "house"},
{"name": "Location 2", kind: "house"},
{"name": "Location 3", kind: "office"},
...
{"name": "Location X", kind: "house"}
]
我想用 .where
查询 JSON 数据类型。
我想查询至少有一个位置为 kind = office
的用户。
谢谢!
最佳答案
I want to query for users that have locations with kind
office
# if locations is jsonb type
User.where('locations @> ?', { kind: 'office' }.to_json)
# if locations is json type
User.where("locations->>'kind' = 'office'")
# if locations is array of hashes
User.where('locations @> ?', [{ kind: 'office' }].to_json)
关于ruby-on-rails - 如何按散列值在 JSON 散列数组中进行搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895445/