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

model#update commits changes in associations when top level model is invalid

      Hello!

      I have question about behaviour of accepts_nested_attributes_for for has_many relations, specifically: removing related objects on assignment if allow_destroy is set and _destroy is passed.

      It seems that the intended behaviour for has_many is indeed to persist changes immediatelly:

      https://github.com/mongodb/mongoid/blob/master/spec/mongoid/attributes/nested_spec.rb#L3066-L3075

      on the other hand, this behaviour is different for embeds_many:

      https://github.com/mongodb/mongoid/blob/master/spec/mongoid/attributes/nested_spec.rb#L1373-L1387

      Most notably, assume following validation on Person model:

      class Person
        include Mongoid::Document
      
        has_many :posts
        accepts_nested_attributes_for :posts, allow_destroy: true
        validates :posts, presence: true
      end
      

      Now it is possible to remove all posts from existing Person, resulting in it to be invalid (since it has no posts) using:

      person.update(posts_attributes: [(_delete all existing posts)])
      

      Update will "fail" (return false), but the Posts will be removed. It doesn't look like correct behaviour

      Best,
      Michał

            Assignee:
            Unassigned Unassigned
            Reporter:
            fanfilmu Micha?
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: