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

deleting a has_and_belongs_to_many relation doesn't nullify properly

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

      I'm experiencing some unexpected behavior when using a has_and_belongs_to_many relation with Mongoid.

      class Team
          include Mongoid::Document
          
          field :name,       :type => String
          field :ip_address, :type => String
          
          has_many :events, :dependent => :destroy
          has_many :flags,  :dependent => :destroy
          has_and_belongs_to_many :quests
          
          validates :name,       :presence => true, :uniqueness => true
          validates :ip_address, :presence => true, :uniqueness => true, :ip_address => true
      end
      
      class Quest
          include Mongoid::Document
          
          field :name,    :type => String
          field :key,     :type => String,  :default => Proc.new { SecureRandom.base64 }
          field :enabled, :type => Boolean, :default => false
          
          has_and_belongs_to_many :teams
          
          validates :name, :presence => true, :uniqueness => true
          validates :key,  :presence => true, :uniqueness => true
      end
      

      Given the above models I would expect the Team <=> Quest relation to be nullified when calling delete_all or clear and
      when setting the relation via the [] accessor as the docs state that the default option is to nullify the realtion.

      clear and [] both work properly.
      The quest_ids and team_ids are both cleared to an empty array
      and calling Team.first.quests from the console gives an empty array.

      However, when calling delete_all
      the quest is deleted from the DB (didn't expect that)
      and the quest_ids for the team are not cleared (definately didn't expect that).

      > Team.create(:name => "test", :ip_address => "192.168.0.1")
      
      > Quest.create(:name => "test")
      
      > Team.first.quests << Quest.first
      
      > Team.first.quests.delete_all
      
      > Quest.first
        => nil
      
      > Team.first.quest_ids
        => [BSON::ObjectId("...")]
      
      > Team.first.quests
        => []
      

      Mongoid: 2.4.8
      Ruby: 1.8.7p357

            Assignee:
            Unassigned Unassigned
            Reporter:
            ghost Deleted user
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: