0

I have a json column in an Answer table in a rails app; document. I'm trying to write a scope which returns true if the document is empty, or if it contains only one of two specific keys.

With ruby we could do something like:

Answer.document.except(:name, :secondary_name).empty?

But I need to use a scope that should behave like this:

a1 = Answer.document => {}
a2 = Answer.document => { name: "anything" }
a3 = Answer.document => { secondary_name: "anything" }
a4 = Answer.document => { other_important_key: "other_important_data" }  

Answers.untouched => [a1, a2, a3]
1
  • See Active Record and PostgreSQL and JSON Functions and Operators. The ActiveRecord query interface doesn't cover querying inside of JSON types as there are two many differences between vendors and dealing with JSON types is a royal PITA. Either use a string, arel or use actual tables instead of JSON.
    – max
    Commented Dec 10, 2024 at 19:07

1 Answer 1

0

In the end I've inverted the query (to return touched answers) using the following:

where("(document::jsonb - 'name' - 'secondary_name') <> '{}'::jsonb")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.