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

Mongoid 8 breaks "build"

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 8.1.0, 9.0.0, 8.0.4
    • Affects Version/s: 8.0.1, 8.0.2, 8.0.3
    • Component/s: None
    • None
    • Fully Compatible

      Starting with Mongoid 8, creating an associated document via build doesn't call its initialize method anymore.

      Here's a small example: (setting a default value is just an example to illustrate the actual problem of initialize being skipped)

      class Foo
        include Mongoid::Document
        embeds_many :bars
      end
      
      class Bar
        include Mongoid::Document
        embedded_in :foo
        field :name, type: String
      
        def initialize(...)
          super
          self.name ||= "default"
        end
      end
      

      The above code results in:

      foo = Foo.new
      
      foo.bars << Bar.new
      foo.bars
      #=> [#<Bar _id: 64392e9c571de67659233fe7, name: "default">]
      
      foo.bars.build
      foo.bars
      #=> [#<Bar _id: 64392e9c571de67659233fe7, name: "default">,
      #    #<Bar _id: 64392e9c571de67659233fe8, name: nil>]
      

      Note that the Bar instance created via build lacks a value for name. Prior to Mongoid 8, both variants behaved identically.

       initialize is a crucial method in Ruby's object lifecycle and shouldn't be skipped.

            Assignee:
            jamis.buck@mongodb.com Jamis Buck
            Reporter:
            mail@stefanschuessler.de Stefan Schüßler
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: