2
votes

Let's say I have a model Neighborhood that has a jsonb[] field families, which is an array containing json objects with any type of key value pairing like so [{"name":"Smiths", "count":4}, {"name":"Miller","out_on_vacation":false}, {"name":"Bennet", "house_color":"red", "count": 4}]

I want to do an activerecord query to find Neighborhoods for Neighborhoods having certain objects inside their families array. So if I did something like Neighborhood.where({families: {count: 4}), the result would be any Neighborhood models whose families field contain a jsonb object with a key value pairing of count: 4. I've played around with a bunch of different queries, but can't seem to get any of them to work without getting an error back. How would I go about writing an Activerecord query to getthe desired results?

EDIT: I had run a migration like so:

def change 
  add_column :neighborhoods, :families, :jsonb, array: true, default: [], index: true 
end
1

1 Answers

0
votes

I believe you would do something like:

Neighborhood.where("families -> 'count' ? 4")

This article might help you: http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

edit: Just noticed that you have an array inside of the jsonb, so this probably won't work.

edit 2: This was answered over on Reddit and worked for me as well. Answering here as a reference for myself.

Neighborhood.where %q(families @> '[{"count":?}]'), 4