Skip to content

Instantly share code, notes, and snippets.

@joelmoss
Created June 5, 2023 08:15
Show Gist options
  • Select an option

  • Save joelmoss/eed7cb45a64df0a09168075aee69e6dc to your computer and use it in GitHub Desktop.

Select an option

Save joelmoss/eed7cb45a64df0a09168075aee69e6dc to your computer and use it in GitHub Desktop.

Revisions

  1. joelmoss created this gist Jun 5, 2023.
    20 changes: 20 additions & 0 deletions fix_active_record_jsonb.rb
    Original 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