Skip to content

Instantly share code, notes, and snippets.

@joelmoss
Created June 5, 2023 08:15
Show Gist options
  • Save joelmoss/eed7cb45a64df0a09168075aee69e6dc to your computer and use it in GitHub Desktop.
Save joelmoss/eed7cb45a64df0a09168075aee69e6dc to your computer and use it in GitHub Desktop.
Make Rails properly decode hashes and arrays in JSONB fields
# See https://til.magmalabs.io/posts/eb568eed39-make-rails-properly-decode-hashes-and-arrays-in-jsonb-fields-the-way-god-intended
ActiveRecord::Type::Json.class_eval do
# this is a json field, thus always decode it
def deserialize(value)
ActiveSupport::JSON.decode(value) rescue nil
end
def serialize(value)
if value.is_a?(::Array) || value.is_a?(::Hash)
::ActiveSupport::JSON.encode(value)
elsif value.is_a?(::String) && value.start_with?("{", "[") && value.end_with?("}", "]")
value
elsif value.respond_to?(:to_json)
value.to_json
else
value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment