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

Inconsistent behaviour for embedded objects callbacks

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None

      Tested on Mongoid 3.1.6.
      Let's do some preparations:

      class Foo
      include Mongoid::Document
      embeds_many :bars
      end

      class Bar
      include Mongoid::Document
      embedded_in :foo
      before_save :baz
      field :qux, type: String
      def baz
      puts "baz launch"
      end
      end

      foo = Foo.new
      foo.bars << Bar.new

      foo.save

      MOPED: 127.0.0.1:27017 INSERT database=overmind_development collection=foos documents=[{"_id"=>"5375c10f32178c4d27000004", "bars"=>[

      {"_id"=>"5375c10f32178c4d27000005"}

      ]}] flags=[] (0.1349ms)

      Now if we change and save the embedded object, we'll get the callback:

      foo.bars[0].qux = "hoge"
      foo.bars[0].save
      baz launch
      MOPED: 127.0.0.1:27017 UPDATE database=overmind_development collection=foos selector=

      {"_id"=>"5375c10f32178c4d27000004", "bars._id"=>"5375c10f32178c4d27000005"}

      update={"$set"=>{"bars.$.qux"=>"hoge"}} flags=[] (0.6673ms)

      But if we do save of the main object, the callback isn't run:

      foo.bars[0].qux = "piyo"
      foo.save
      MOPED: 127.0.0.1:27017 UPDATE database=overmind_development collection=foos selector=

      {"_id"=>"5375c10f32178c4d27000004"}

      update={"$set"=>{"bars.0.qux"=>"piyo"}} flags=[] (0.1249ms)

      This makes using callbacks on embedded objects pretty useless. I think that if you save the main object, then all the modified embedded objects must have their callbacks run.

            Assignee:
            Unassigned Unassigned
            Reporter:
            exoth Yuriy Trofimenko
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: