4

I am using a JSONB column where the data is stored as { key => [value, value, value ] } How do I write a scope that returns records which contain a particular value in the array of a particular key?

I've figured out how to search simple JSON Hashes;

scope :rice_flour, -> { where("ingredients ->> 'flour' = ?", "rice") }

...but this query type still escapes me. Everything I have looked up lays things out in raw SQL commands, and I am looking for how to write tidy Rails Scopes.

3
  • "particular value in it's hash" you mean "particular value in the array"? Commented Dec 5, 2018 at 22:41
  • what is your postgres version? Commented Dec 5, 2018 at 22:41
  • Meant I want to query for records containing a particular value in the array of a particular key. Postgres 10.6 Commented Dec 5, 2018 at 23:00

1 Answer 1

4

Use the @> operator:

postgres@/> select '["a", "b"]'::jsonb @> '["a"]';
+------------+
| ?column?   |
|------------|
| True       |
+------------+

postgres@/> select '["a", "b"]'::jsonb @> '["c"]';
+------------+
| ?column?   |
|------------|
| False      |
+------------+

https://www.postgresql.org/docs/10/functions-json.html

Your scope will be like:

scope :rice_flour, -> { 
   .where("ingredients -> 'flour' @> '[\"rice\"]'::jsonb")
}

This will generate a SQL like:

WHERE (ingredients -> 'flour' @> '["rice"]'::jsonb)

Assuming flour is the key and rice is one of the values in the array.

Sign up to request clarification or add additional context in comments.

1 Comment

I am one reputation short of being able to Vote for your answer. :-/ Thanks emaillenin for the information and pointer. Works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.