Querying a nested array of hashes for existence of a key in jsonb postgres with activerecord
<p>I'm using the jsonb datatype in postgres to store various variable settings for a model. </p>

<p>With hashes it seems pretty straightforward. </p>

<p>If I create: </p>

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

<p>If I do something a little more complex with mutiple keys: </p>

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

Model.where("settings -&gt; 'a' ? 'b' ") #or
=&gt; Model...
Model.where("settings -&gt; 'a' ? 'd' ")
=&gt; Model...
</code></pre>

<p>does likewise</p>

<p>Now if I put an array at the top level, I can do the following: </p>

<pre><code>Model.create(settings:["a","b"])
Model.where("settings ? "a")
=&gt; Model...
</code></pre>

<p>and get the object returned.</p>

<p>And with a nested array. </p>

<pre><code>Model.create(settings:{a:["a","b"]})
Model.where("settings -&gt; 'a' ? 'a'")
=&gt; Model...
Model.where("settigns -&gt; 'a' ? :v", v: 'a')
=&gt; Model...
</code></pre>

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

<pre><code>Model.create(settings:[{a:"b"}, {c:"d"}])
Model.where("settings ? :v", v: {a:"b"})
=&gt; []
Model.create(settings:{a:[{b:"c"}, {d:"e"}]})
Model.where("settings -&gt; 'a' ? :v", v: {b:"c"})
=&gt; []
</code></pre>

<p>all fail to return the object.</p>

<p>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.</p>