Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query jsonb array field in Rails 5

How to use active record to query an array of jsonb objects

Schema

 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 Console



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


like image 417
Kelvin Smith Avatar asked Jul 19 '19 19:07

Kelvin Smith


1 Answers

This was answered well in this SO post:

Query on Postgres JSON array field in Rails

For the question in this post, this should work to find where "to" = "Yaba Lagos":

Route.where('travel_routes @> ?', '[{"to": "Yaba Lagos"}]')
like image 75
B-Rad Avatar answered Oct 20 '22 06:10

B-Rad