Rails 5中如何查询jsonb数组字段

7
如何使用Active Record查询一个JSONB对象数组
架构
 create_table "routes", force: :cascade do |t|
    t.string "state"
    t.text "address"
    t.bigint "user_id", null: false
    t.jsonb "travel_routes", array: true
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_routes_on_user_id"
  end

Rails控制台



travel_routes: [{"to"=>"Yaba Lagos", "fee"=>5000}, {"to"=>"Lagos Iyanapaja", "fee"=>3000}]



你想针对这个JSONB列查询什么? - Arup Rakshit
是的,我想使用Active Record针对JSONB列进行查询。 - Kelvin Smith
你确定PostgreSQL不支持jsonb数组吗?因为它可以很好地接受我的输入,只是查询数据有点麻烦。基于上述数据,你能给我展示一些如何查询json[]数组的例子吗? - Kelvin Smith
2个回答

14

这个问题在这篇SO帖子中得到了很好的回答:

Query on Postgres JSON array field in Rails

对于这篇文章中的问题,以下代码应该可以找到 "to" = "Yaba Lagos" 的位置:

Route.where('travel_routes @> ?', '[{"to": "Yaba Lagos"}]')

8
这也可以这样实现:
Route.where('travel_routes @> ?', [{to: "Yaba Lagos"}].to_json)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接