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

Setting an association to an empty array is deleting the associed record

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

      Hi guys,

      sorry for always report bugs =/

      Now I isolated the failure case in an test. I'm using Mongoid 2.1.8.

      require 'rubygems'
      require 'mongoid'
      require 'rspec'
      
      Mongoid.config.database = Mongo::Connection.new.db("test")
      
      describe "Associations" do
        before do
          class User
            include Mongoid::Document
            field :name, :type => String
          end
      
      
          class Person
            include Mongoid::Document
      
            has_and_belongs_to_many :users
          end
        end
      
        let!(:user) { User.create!(:name => "rafael") }
        let!(:person) { Person.create!(:users => [user]) }
      
        after do
          User.destroy_all
          Person.destroy_all
        end
      
        context "setting to empty array" do
          it "doesn't remove the User" do
            expect { person.users = [] }.to_not change(User, :count)
          end
        end
      
        context "setting to nil" do
          it "doesn't remove the User" do
            expect { person.users = nil }.to_not change(User, :count)
          end
        end
      end
      

      When I run the tests it returns:

      Failures:
      
        1) Associations setting to empty array doesn't remove the User
           Failure/Error: expect { person.users = [] }.to_not change(User, :count)
             count should not have changed, but did change from 1 to 0
           # ./mongoid-test.rb:32
      
        2) Associations setting to nil doesn't remove the User
           Failure/Error: expect { person.users = nil }.to_not change(User, :count)
             count should not have changed, but did change from 1 to 0
           # ./mongoid-test.rb:38
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            rafaelfranca rafaelfranca
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: