2

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
0

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
2
  • hmmmm, this still isn't working for me for some reason, I made a migration to add the jsonb[] column which I have posted in the question under the edit header. whenever I try Neighborhood.where %q(families @> '[{"count":?}]'), 4 I get a ERROR: malformed array literal and a detail saying "[" must introduce explicitly-specified array dimensions. did you know why this would be by any chance? Oct 19, 2016 at 17:47
  • did you use an index by any chance? Oct 19, 2016 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.