1

I have a few User records with a details json column that look like this:

User.create(details: {accounts: [{name: 'one', id: 1}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'four', id: 4}])

How do I query for all records where id is 2?

RandallB
  • 5,415
  • 6
  • 34
  • 47
  • check here https://stackoverflow.com/questions/22667401/postgres-json-data-type-rails-query OR here http://edgeguides.rubyonrails.org/active_record_postgresql.html#json – LHH Dec 06 '17 at 12:38

1 Answers1

0

Thanks to Using jsonb (PostgreSQL), how do I retrieve items with a certain value that's saved as an array? I was put on the right track.

The query to match:

User.where("? in (SELECT json_array_elements(details->'accounts')->>'id')", "2")
RandallB
  • 5,415
  • 6
  • 34
  • 47