8

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}]


3
  • What you want to query against this JSONB column? Commented Jul 19, 2019 at 19:56
  • Yes I want to query against the JSONB column using Active Record Commented Jul 19, 2019 at 20:36
  • Are you sure PostgreSQL does not support jsonb Array, because it is accepting my inputs very fine, just querying the data that is a bit of a headache. How would I query a json[] array, any examples you could show me based on the data above. Commented Jul 20, 2019 at 8:18

2 Answers 2

14

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"}]')
Sign up to request clarification or add additional context in comments.

Comments

8

It also works this way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.