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

Nested attributes with allow_destroy destroy nested associations when host save fails due to validation errors

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 5.4.0, 6.4.4, 7.0.5
    • Component/s: Validations
    • None
    • Environment:
      Debian GNU/Linux 9 (stretch) 64-bit, Intel® Coreā„¢ i7-8700 CPU @ 3.20GHz × 12, 15.6 GiB , ruby on rails 6.0.0

      I am having an unexpected behavior when I am trying to update a nested relation that has some validation errors, I have a `has_many` relation between two entities (Dog and flea), and both models has their own validations as follows:

      dog.rb
      #Dog
      class Dog
        include Mongoid::Document
        field :name
        has_many :fleas, class_name: 'Flea'
        validates :name, presence: true
        accepts_nested_attributes_for :fleas, allow_destroy: true
      end
      
      flea.rb
      #Flea
      class Flea
        include Mongoid::Document
        field :name
        belongs_to :dog, class_name: 'Dog'
        validates :name, presence: true
      end
      

      Using `nested_attributes` I have created 1 dog that has 2 fleas

      d = Dog.create(name: 'Lulu', fleas_attributes: { 0 => { name: 'Tiny' }, 1 => { name: 'molly' } })
      #get the persisted fleas
      d.fleas
      #Fleas
      {
        {
          :_id => BSON::ObjectId('5df40b96a5717a2ba148b25b'),
          :dog_id => BSON::ObjectId('5df40b96a5717a2ba148b25c'),
          :name => "Tiny"
        },
        {
          :_id => BSON::ObjectId('5df40b96a5717a2ba148b25d'),
          :dog_id => BSON::ObjectId('5df40b96a5717a2ba148b25c'),
           :name => "molly"
         }
      }
      

      Finally, I made an update using the dog instance without a name (breaking the presence validation associated to :name)

         d.update(name: '', fleas_attributes: { 0 => { name: 'Tiny', _destroy: '1', id:
         '5df40b96a5717a2ba148b25b' }, 1 => { name: 'molly', id:
          '5df40b96a5717a2ba148b25d' } })
           #response
      {color:red}
           =>false
      {color}
      

      At the end, when I make a query for getting all the fleas associated to my dog, I got only one flea although the validation of the parent model has failed, that behavior is confused and it could be considered dangerous and tricky in more complex scenarios with more robust validations

       d.fleas
      #response
      #_id|name |dog_id
      5df40b96a5717a2ba148b25d | molly | 5df40b96a5717a2ba148b25c
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            camilo.echeverri@analisistem.com Camilo Echeverri
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: