Search code examples
ruby-on-railsmongoid3

Mongoid embedded documents not maintaining reference?


So this behavior is counter to what I would have expected. Let's say I have a document that has 1-n embedded images (well, the metadata for the images). I notice that if I do this:

doc.images.first.alt = 'some alt text'
doc.save

everything works as normal. If I first get a ref to the image:

i = doc.images.first
i.alt = 'some alt text'
doc.save # and/or i.save

The alt text is not saved. Is that the expected behavior?


Solution

  • Assigning docs.images.first to a var means you are changing that variable, not the originating object.

    Think of it like a nested hash

    a = { x: 1, y: { z: 3 }}
    

    If you set:

    b = a[:y]
    

    Changing stuff in b does not affect a.