Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dereknguyen269/f9b86753f5e901635a367c34c712387a to your computer and use it in GitHub Desktop.
Save dereknguyen269/f9b86753f5e901635a367c34c712387a to your computer and use it in GitHub Desktop.
Queries And Update Property In JSON Column With Rails
# Table Driver
# Id : Integer
# Name : String
# Vehicle Attributes : JSON
# Example:
# {
# id: 1,
# name: 'Driver Name',
# vehicle_attributes: {
# vehicle_color: 'Black',
# vehicle_name: 'Honda',
# vehicle_plate_number: '123456789'
# }
# }
# Find Drivers who have vehicle with black color
drivers = Driver.where("vehicle_attributes->>'vehicle_color' LIKE ?", "%black%")
# Update Drivers who have vehicle with black color into white
drivers.update_all("vehicle_attributes = jsonb_set(\"vehicle_attributes\"::jsonb, '{vehicle_color}', '\"white\"')")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment