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

Parent validation fired when saving child with validates_presence_of :parent

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.0.2
    • Affects Version/s: None
    • Component/s: None
    • None

      Hi

      I have a strange behaviour on validation with 1:n relation.

      I have 2 classes, with 1:n relation, and a validates_presence_of :parent on the child ;

      require 'mongoid'
      
      Mongoid.connect_to("mongoid_perf_test")
      Mongoid.purge!
      
      class Parent
        include Mongoid::Document
        field :name, :type => String
        has_many :child, :validate => true
        validates_presence_of :name
        before_validation :before_validation
      
        def before_validation
          puts "Valid Parent"
        end
      end
      
      class Child
        include Mongoid::Document
        field :name, :type => String
        belongs_to :parent
        validates_presence_of :name, :parent
        before_validation :before_validation
      
        def before_validation
          puts "Valid Child"
        end
      end
      
      parent = Parent.new({name: "Name"})
      parent.save!
      
      
      3.times do
        child = Child.new({name: "Name"})
        child.parent = parent
        child.save!
      end
      

      results :

      Valid Parent
      Valid Child
      Valid Parent
      Valid Child
      Valid Child
      Valid Parent
      Valid Child
      Valid Child
      Valid Child
      Valid Parent
      Valid Child
      Valid Child
      Valid Child
      

      The parent validation callback is fired each time i save the child, and, because of the :validate on the relation, every children are re-validate every time i append a new child.

      Is the normal behaviour, or a bug?

            Assignee:
            durran.jordan@mongodb.com Durran Jordan
            Reporter:
            MickaelMagniez MickaelMagniez [X]
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: