简体   繁体   English

Rails:查询Postgres的JSON数组

[英]Rails: Querying Postgres for JSON Array

I am using Rails (4.2) and the Postgres JSON data type to store arrays: 我正在使用Rails(4.2)和Postgres JSON数据类型来存储数组:

#<Mapping:0x007fa3b6263390 foo: ["bar", baz]>

Now I want to query for all mappings with a specific array: 现在,我要查询具有特定数组的所有映射:

Mapping.where(foo: ["bar", "baz"])

Turns out this does not work. 原来这行不通。 What query can I use to find what I want? 我可以使用什么查询找到我想要的? All the JSON query examples are usually for hashes, not for arrays (at least not at the top level). 所有JSON查询示例通常都是针对哈希,而不是数组(至少不是在顶层)。

ActiveRecord has built-in support for Postgres arrays. ActiveRecord具有对Postgres数组的内置支持

# equality
Book.where("tags = ARRAY[?]::varchar[]", ["fantasy", "fiction"])

# inclusion
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

There are quite a lot of array functions available, check them out here . 有很多可用的数组函数,请在此处查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM