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

Preventing a NoMethodError when calling #as_document on an embedded relation that is nil.

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

      If you have an embeds_one relationship that at some point gets set to nil, calling #as_document on the model will cause a NoMethodError. I ran into this where my destroy callback ended up calling #as_document and I got this error:

      p = Person.new(title: "Sir")
      p.build_name(first_name: "James")
      p.save
      p.name = nil
      p.save
      p.reload
      
      # This line will throw a NoMethodError
      p.as_document
      

      This patch fixes it and adds a spec.

      Also, in doing this, I realized that the "as_document" doesn't update until the document is re-pulled from Mongo. That is, in my above example if you don't call p.reload, then p.as_document will return {{{ "name" :

      {"first_name" : "James" }

      }}} even if the document is saved. @durran, is this expected behavior? Seems like a bug but wanted to ask you first.

            Assignee:
            Unassigned Unassigned
            Reporter:
            jonhyman Jon Hyman
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: