Created
June 5, 2023 08:15
-
-
Save joelmoss/eed7cb45a64df0a09168075aee69e6dc to your computer and use it in GitHub Desktop.
Make Rails properly decode hashes and arrays in JSONB fields
This file contains 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
# 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