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}]
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"}]')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With