Reputation: 81
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}]
Upvotes: 8
Views: 19551
Reputation: 16074
It also works this way:
Route.where('travel_routes @> ?', [{to: "Yaba Lagos"}].to_json)
Upvotes: 8
Reputation: 211
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"}]')
Upvotes: 14