Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-2279

cascade callbacks broken for before save on embedded documents

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.0.4
    • Affects Version/s: None
    • Component/s: None
    • None

      The following scenario fails in 3.0

      In short, I need a hash to get seriaized and deserialized before save and after initialize. The after init works, but the before save never hits.

        class TestSubject
          include Mongoid::Document
      
          embeds_one :response_body,
                     class_name: "SerializedHash",
                     as: :needs_hash,
                     cascade_callbacks: true
      
          after_initialize :initialize_hash
      
          def initialize_hash
            self.response_body ||= SerializedHash.new
          end
      
        end
      
      class SerializedHash
        include Mongoid::Document
      
        embedded_in :needs_hash, polymorphic: true
        field :serialized_hash, type: String, default: ""
      
      
        before_save :serialize_hash
        after_initialize :deserialize_hash
      
        attr_reader :hash_back
        delegate :[], :[]=, :size, :each, :to => :hash_back
      
      
        def deserialize_hash
          if serialized_hash && ! serialized_hash.empty?
            @hash_back = Marshal.load serialized_hash
          else
            @hash_back = {}
          end
        end
      
        def serialize_hash
          puts "before save"
          self.serialized_hash = Marshal.dump(@hash_back)
        end
      
      end
      
        test "can serialize hash" do
          subject = TestSubject.create
      
          subject.response_body["a"] = 0
          subject.response_body["b"] = 1
      
          assert_equal({"a" => 0, "b" => 1}, subject.response_body.hash_back)
          sh = Marshal.dump subject.response_body.hash_back
          puts "saving!"
          subject.save
      
          assert_equal({"a" => 0, "b" => 1}, subject.response_body.hash_back)
          assert_equal sh, subject.response_body.serialized_hash
          subject.reload
          assert_equal({"a" => 0, "b" => 1}, subject.response_body.hash_back)
        end
      

            Assignee:
            durran Durran Jordan
            Reporter:
            ryanmcgarvey ryanmcgarvey
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: