# 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