Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Rails, JSON - match results if key exists

The set up is ruby on rails, in a postgres database. The table is called line_sources and a JSON column is called names. I want to return all rows where the names column contains a key called away_names. I'm trying this but they fail:

LineSource.where("names -> 'away_names'")

and

LineSource.where("names ->> 'away_names' = '%'")
like image 952
appleLover Avatar asked Aug 15 '15 21:08

appleLover


2 Answers

Try this :

where("(names->'away_names') is not null")
like image 167
Nicolas Maloeuvre Avatar answered Nov 01 '22 14:11

Nicolas Maloeuvre


You can use #> to get the JSON object at that path.

where("(names #>'{away_names}') is not null")

Basic key operators to query the JSON objects :

  • #> : Get the JSON object at that path
  • ->> : Get the JSON object at that path as text
  • {obj, n} : Get the nth item in that object
like image 22
pramod Avatar answered Nov 01 '22 13:11

pramod