LoginSignup
5
1

More than 3 years have passed since last update.

Rails + postgres で jsonb の中の Array をクエリする方法

Posted at

難しかったのでメモ

データの形

こんな感じのが jsonb のカラムの中に保存されている。

{
  hoge: String,
  items: String[]
}

やりたいことと解決策

それでやりたいのは items の中に特定の文字列 ["a", "b", "c"] のいずれかが含まれているものをクエリすること。

結論としては次のようなコードでいけた。

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

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1