Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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,
Model.where(id:["options = options || ?::jsonb", new_option])
# Additional reading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment