简体   繁体   中英

rails AR query filtering records using postgres json data type

My postgres json data looks like this:

changes: {"data"=>[nil, {"margin"=>0.0, "target"=>0.77777}]}

The field name is changes and it's a postgres json data type.

How do I write an active record query to check for rows where data has a key named margin ?

For example, the first record would be included while the second would not:

# record 1
changes: {"data"=>[nil, {"margin"=>0.0, "target"=>0.77777}]}
# record 2
changes: {"data"=>[nil, {"foo"=>0.0, "target"=>0.77777}]}

I've tried something like the following but it's not working:

ModelName.where("changes -> 'data' ?| array[:keys]", keys: ['margin'])

Okay, this is what I found

Query based on JSON document

The -> operator returns the original JSON type (which might be an object), whereas ->> returns text

Also, this post is probably what you look for.

Maybe try something like

ModelName.where("changes->>'margin' > -1")

The answer:

ModelName.where("changes -> 'data' -> 1 ? 'margin'")

The query logic is something like...in the changes field, move to object data , get second element (zero based index), see if it contains a key named margin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM