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

Kel*_*ith 4 postgresql activerecord ruby-on-rails

如何使用活动记录查询一组 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
Run Code Online (Sandbox Code Playgroud)

Rails 控制台



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


Run Code Online (Sandbox Code Playgroud)

Jan*_*Jan 8

它也可以这样工作:

Route.where('travel_routes @> ?', [{to: "Yaba Lagos"}].to_json)
Run Code Online (Sandbox Code Playgroud)


小智 6

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

在 Rails 中查询 Postgres JSON 数组字段

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

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