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'])
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.