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

remove_instance_variable error in One#nullify

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

      In some cases nullify tries to remove an instance variable that doesn't exist. Here's an example:

      class User
        include Mongoid::Document
        field :name 
        belongs_to :photo
      end
      
      class Photo
        include Mongoid::Document
        field :name 
        has_one :user, dependent: :nullify
      end
      

      This works:

      user = User.create(name: "john")
      photo = Photo.create(name: "my cat")
      user.photo = photo
      user.save
      photo.destroy
      

      But this doesn't:

      user = User.create(name: "john")
      photo = Photo.create(name: "my cat")
      user.photo = photo
      user.save
      photo = Photo.find("the photo's id")
      photo.destroy
      
      NameError: instance variable @photo not defined
      	from mongoid-2.0.2/lib/mongoid/relations/referenced/one.rb:71:in `remove_instance_variable'
      	from mongoid-2.0.2/lib/mongoid/relations/referenced/one.rb:71:in `nullify'
      	from mongoid-2.0.2/lib/mongoid/relations/cascading/nullify.rb:13:in `cascade'
      	from mongoid-2.0.2/lib/mongoid/relations/cascading.rb:32:in `block in cascade!'
      	from mongoid-2.0.2/lib/mongoid/relations/cascading.rb:29:in `each'
      	from mongoid-2.0.2/lib/mongoid/relations/cascading.rb:29:in `cascade!'
      	from mongoid-2.0.2/lib/mongoid/persistence.rb:62:in `remove'
      	from mongoid-2.0.2/lib/mongoid/persistence.rb:34:in `block in destroy'
      	from activesupport-3.0.7/lib/active_support/callbacks.rb:419:in `_run_destroy_callbacks'
      	from activesupport-3.0.7/lib/active_support/callbacks.rb:94:in `run_callbacks'
      	from mongoid-2.0.2/lib/mongoid/persistence.rb:34:in `destroy'
      

      However, if user.photo is accessed before destroying the photo then @photo gets set and no exception is thrown.

      The simplest fix is probably to check instance_variable_defined? in nullify before calling remove_instance_variable.

            Assignee:
            Unassigned Unassigned
            Reporter:
            ianiv Ianiv Schweber
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: