Postgres JSON data type Rails query

前端 未结 3 1944
孤城傲影
孤城傲影 2020-11-28 19:40

I am using Postgres\' json data type but want to do a query/ordering with data that is nested within the json.

I want to order or query with .where on the json data

3条回答
  •  囚心锁ツ
    2020-11-28 19:50

    According to this http://edgeguides.rubyonrails.org/active_record_postgresql.html#json there's a difference in using -> and ->>:

    # db/migrate/20131220144913_create_events.rb
    create_table :events do |t|
      t.json 'payload'
    end
    
    # app/models/event.rb
    class Event < ActiveRecord::Base
    end
    
    # Usage
    Event.create(payload: { kind: "user_renamed", change: ["jack", "john"]})
    
    event = Event.first
    event.payload # => {"kind"=>"user_renamed", "change"=>["jack", "john"]}
    
    ## Query based on JSON document
    # The -> operator returns the original JSON type (which might be an object), whereas ->> returns text
    Event.where("payload->>'kind' = ?", "user_renamed")
    

    So you should try Record.where("data ->> 'status' = 200 ") or the operator that suits your query (http://www.postgresql.org/docs/current/static/functions-json.html).

提交回复
热议问题