【问题标题】:How to query jsonb array field in Rails 5如何在 Rails 5 中查询 jsonb 数组字段
【发布时间】:2019-07-19 19:52:35
【问题描述】:

如何使用活动记录查询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

Rails 控制台



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


【问题讨论】:

  • 您要针对此 JSONB 列查询什么?
  • 是的,我想使用 Active Record 查询 JSONB 列
  • 你确定PostgreSQL不支持jsonb数组,因为它接受我的输入非常好,只是查询数据有点头疼。我将如何查询 json[] 数组,您可以根据上面的数据向我展示任何示例。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

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

Query on Postgres JSON array field in Rails

对于这篇文章中的问题,这应该可以找到 where "to" = "Yaba Lagos":

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

【讨论】:

    【解决方案2】:

    它也可以这样工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2015-04-13
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多