6

I have a JSON column in my events table called payload. I can create an event like this:

Event.create!(application_id: 1, stage: 'INITIATION', payload: { key: 'OUTCOME', value: {school_id: 2, prefered_language: 'GBP'}})

Simple queries like

Event.where("payload->>'key' = ?", "OUTCOME")

Will work fine, but how can I then add extra filters with the JSON that's nested in the value portion

 Event.where("payload->>'key' = ? AND payload ->>'value'->>'school' = ?", "OUTCOME", 2) 
                                                 ^^^^^^^^^^^^^^^^^^^^

I tried that but i got:

PG::UndefinedFunction: ERROR:  operator does not exist: text ->> unknown
LINE 1: ...ad ->>'key' = 'INPUTPARAMS' AND payload ->>'value'->>'school...                                                         ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

How do I get into the school attribute within value?

I have taken the idea from this documentation on ActiveRecord and JSON

1 Answer 1

7

After much searching, I came across this article.

The #>> operator allows you to dig inside the JSON. My query could be fixed like this.

Event.where("payload->>'key'= ? AND payload#>>'{value, school_id}' = ?", 'OUTCOME', shcool_id)

You could theoretically go down further by adding each layer to the predicate block {value, school, next_level, and_so_on}

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.