[Ruby] How to query Array in jsonb with Rails + postgres

less than 1 minute read

It was difficult so memo

Data shape

This kind of thing is stored in the jsonb column.

   hoge: String,
   items: String[]

What you want to do and the solution

What you want to do is query for items that contain any of the specific strings ["a", "b", "c"].

In conclusion, I could use the following code.

items_to_query = ["a", "b", "c"]
Model.where("jsonbColumnName ->'items' @> ?", items_to_query.to_json)


https://stackoverflow.com/questions/35737931/rails-postgres-query-with-jsonb-array https://www.postgresql.org/docs/9.4/functions-json.html

Tags: ,