Rails Postgres过滤jsonb数组中的jsonb对象



假设我有一个模型Neighborhood,它有一个jsonb[]字段families,这是一个包含json对象的数组,具有任何类型的键值配对,如[{"name":"Smiths", "count":4}, {"name":"Miller","out_on_vacation":false}, {"name":"Bennet", "house_color":"red", "count": 4}]

我想做一个activerecord查询,以找到在其families数组内具有某些对象的社区。因此,如果我做了类似Neighborhood.where({families: {count: 4})的事情,结果将是任何Neighborhood模型,其families字段包含具有count: 4键值对的jsonb对象。我已经玩了一堆不同的查询,但似乎不能得到任何工作没有得到一个错误回来。我该如何写一个Activerecord查询来获得想要的结果?

编辑:

我运行了这样一个迁移:

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

我相信你会这样做:

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

本文可能对您有所帮助:http://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

编辑:只是注意到你在jsonb里面有一个数组,所以这可能不会工作。

这个问题在Reddit上得到了解答,对我来说也很有用。这里的回答作为我自己的参考。
Neighborhood.where %q(families @> '[{"count":?}]'), 4

最新更新