Search code examples
ruby-on-railsrubypostgresqljsonb

Search in nested Postgresql JSONB column


How to search in nested jsonb column in Rails.

Model: Shop
jsonb column: shop_data

shop_data: {
  common_data: {
    "image_url" => "https://sample.com/img.jpg"
    "token" => "AOsa2123ASDasdaasasda"
    "uid" => ""
    "expires_at" => ""
  }
}

Wanna make a scopes that will checks for records where:

1. shop_data->common_data->expires_at IS NOT NULL
2. shop_data->common_data->image_url IS NULL

Solution

  •  1. scope :expired, -> { where("shop_data -> 'common_data' ->> 'expires_at' IS NOT NULL") }
     2. scope :null_image, -> { where("shop_data -> 'common_data' ->> 'image_url' IS NULL") }
    

    source JSON functions in postgres

    Hope it helps