belongs_to do not respect validate: false for non optional

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Unresolved
    • Priority: Unknown
    • None
    • Affects Version/s: 8.0.1
    • Component/s: Associations, Validations
    • None
    • None
    • Ruby Drivers
    • None
    • None
    • None
    • None
    • None
    • None

      Since commit #13044a8 related to MONGOID-4160 it is no more possible use `validate: false` on a loaded `belongs_to` relation if not used with `required: false` or `optional: true`.

      It is the acknowledge and expected behavior of the library or a bug ? Since docs do not mention this kind of behaviors: https://www.mongodb.com/docs/mongoid/current/data-modeling/associations/#validations

      Also, there is more, I guess this is for performance but when (re-)assigning the relation_id directly (not giving loaded instance), it do not result in validation of the relation.

      Example:

      class HomParent
        include Mongoid::Document
        has_many :children
      
        field :name, type: String
        field :label, type: String
      
        validates :name, presence: true
        validates :label, presence: true
      end
      
      class HomChild
        include Mongoid::Document
        belongs_to :parent, class_name: 'HomParent'
      end
      
      hom_parent = HomParent.create(name: 'parent', label: 'Parent')
      hom_parent.update_attribute(:label, nil)
      hom_parent.reload
      hom_parent.persisted? # => true
      
      hom_child = HomChild.new
      hom_child.parent = hom_parent
      hom_child.save # => false
      hom_child.errors # => #<ActiveModel::Errors [#<ActiveModel::Error attribute=parent, type=invalid, options={}>]>
      
      hom_child.parent_id = hom_parent.id
      hom_child.save # => true
      
      hom_child.reload
      hom_child.persisted? # => true
      hom_child.parent.invalid? # => true
      

            Assignee:
            Unassigned
            Reporter:
            Paul Guillemot
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: