lezayskincoach
lezayskincoach

Reputation: 21

How to query nested json attribute on postgres / ruby on rails

My json for an attribute in a record looks as so:

 { foo: bar,   
   foo1: [{key1: value, key2: value},
         {key1: value, key2: value}]
  }

i can query for foo just fine by using

Model.where("attribute->>'foo' = ?", "bar")

Having some trouble querying for values in in key1 and key2

Upvotes: 2

Views: 1702

Answers (1)

Gabriel Mesquita
Gabriel Mesquita

Reputation: 2391

Take a look here postrgeSQL

You can use this operator #>> to perform what you need, as the link says 'Get JSON object at specified path as text', for example:

'{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'

Model.where("attribute#>>'{foo1, key1}' = ?", "bar")

You should just adapt to your needs now. Hope it helped!

Upvotes: 2

Related Questions