Skip to content

Instantly share code, notes, and snippets.

@ismailmechbal
Forked from skunkworker/append_json_column_rails_5.rb
Created June 13, 2020 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismailmechbal/1529ea2b370fab909c95abe134b03c73 to your computer and use it in GitHub Desktop.
Save ismailmechbal/1529ea2b370fab909c95abe134b03c73 to your computer and use it in GitHub Desktop.
How to append to a json column array in Rails 5.
# assuming Model is your model and options is a json/jsonb column.
# This uses the Postgres json append || operator.
# And wraps the option inside an array.
# producing [{},{}] multiple hashes inside a top level json array.
# It is very important that the hash is [{}] NOT {} as not having the array on the
# outside will cause the hash to replace the contents instead of appending to them.
new_option = [{
name: option_name,
time: Time.now.iso8601
}].to_json
Model.where(id: model.id).update_all(["options = options || ?::jsonb", new_option])
# Additional reading
# https://stackoverflow.com/questions/42233542/appending-pushing-and-removing-from-a-json-array-in-postgresql-9-5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment