Created
June 5, 2023 08:15
-
-
Save joelmoss/eed7cb45a64df0a09168075aee69e6dc to your computer and use it in GitHub Desktop.
Revisions
-
joelmoss created this gist
Jun 5, 2023 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,20 @@ # 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