-
-
Save ismailmechbal/1529ea2b370fab909c95abe134b03c73 to your computer and use it in GitHub Desktop.
How to append to a json column array in Rails 5.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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