简体   繁体   中英

How to query json data with hashes inside array in rails?

I have the following set of data on the Note model. Currently, I am using the Postgres for the database. Below are two different records on the Notes table.

id: 1,
name: 'First Note',
items: [{description: 'First Note'}, {description: 'PM1 Second Note'}]

id: 2,
name: 'Second Note',
items: [{description: 'Second Note'}, {description: 'PM2 Second Note'}]

id: 3,
name: 'Third Note',
items: [{description: 'Third Note'}, {description: 'Invalid Second Note'}]

How do I query json field (items) such that I get all the notes with the value PM on the description field ie the query should return notes with id 1 and 2 from the above example?

With raw SQL you can achieve with the below:

select * from notes,
  json_array_elements(items) element
  where element->>'description' LIKE '%PM%';

Try the below with activerecord:

Note.where("EXISTS (SELECT FROM json_array_elements(items) element WHERE element->>'description' LIKE '%PM%')")

I didn't test, but one of the following should work.

Note.where("items->>'description' iLIKE ?", '%PM%')
# or
Note.where("items::json -> 'description' iLIKE ?", '%PM%')

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