On a hypothetical books table with a json column called internal, I want to summon the records that do and (separately) do not have a rating key.
1 Answer
Exists:
Book.where('internal::jsonb ? :key', key: 'rating')
Do not exist:
Book.where.not('internal::jsonb ? :key', key: 'rating')
See table called "Additional jsonb Operators":
jsonb ? text → boolean
Does the text string exist as a top-level key or array element within the JSON value?
'{"a":1, "b":2}'::jsonb ? 'b' → t
'["a", "b", "c"]'::jsonb ? 'b' → t
1 Comment
mu is too short
But be careful when using the
? operator with placeholders, you'll want to use named placeholders: where('internal::jsonb ? :key', key: 'rating').