简体   繁体   中英

Querying a nested array of hashes for existence of a key in jsonb postgres with activerecord

I'm using the jsonb datatype in postgres to store various variable settings for a model.

With hashes it seems pretty straightforward.

If I create:

Model.create(settings:{a:"b", c:"d"})
Model.where("settings -> 'a' ? 'b'") #or
=> Model...
Model.where("settings -> 'c' ? 'd'") #or if I just want to check the keys
=> Model...
Model.where("settings ? 'a'")
=> Model...

If I do something a little more complex with mutiple keys:

Model.create(settings:{a:{b:"c", d:"e"}})

Model.where("settings -> 'a' ? 'b' ") #or
=> Model...
Model.where("settings -> 'a' ? 'd' ")
=> Model...

does likewise

Now if I put an array at the top level, I can do the following:

Model.create(settings:["a","b"])
Model.where("settings ? "a")
=> Model...

and get the object returned.

And with a nested array.

Model.create(settings:{a:["a","b"]})
Model.where("settings -> 'a' ? 'a'")
=> Model...
Model.where("settigns -> 'a' ? :v", v: 'a')
=> Model...

But as soon as I put anything more complex in that array I can't seem to get a match anymore.

Model.create(settings:[{a:"b"}, {c:"d"}])
Model.where("settings ? :v", v: {a:"b"})
=> []
Model.create(settings:{a:[{b:"c"}, {d:"e"}]})
Model.where("settings -> 'a' ? :v", v: {b:"c"})
=> []

all fail to return the object.

I'd like to get to the point where I can query the elements of a nested array for whether they have certain keys in their contained hashes, but I can't get around this issue. I'm obviously missing something syntactically, but I can't work out what it is.

In this case Model.create(settings:[{a:"b"}, {c:"d"}])

You could query for it this way: Model.where("settings @> ?", {a: "b"}.to_json)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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