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

Update bypasses validation

    • Type: Icon: Bug Bug
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • 9.1.0
    • Affects Version/s: 7.3.5, 7.4.3, 8.0.6, 8.1.2, 7.5.4
    • Component/s: Attributes, Validations
    • None

      Let's say I have an application with a has_and_belongs_to_many relation between a Client model and a Company model.

      In the Client model there is a validation to make sure the object is associated with at least one company (companies cannot be blank).

      The thing is, when I try to update a client with an empty list of companies, despite raising a validation error message, the invalid model is updated in the database.

      Is this an expected behavior?

      One can reproduce it by running the following code:

      class Company
        include Mongoid::Document
      
        field :name, type: String
      end
      
      class Client
        include Mongoid::Document
      
        field :name, type: String
      
        has_and_belongs_to_many :companies, class_name: 'Company'
      
        validates :companies, presence: true
      end
      
      c = Client.first
      c.update!(companies: []) # raises error but updates document
      

            Assignee:
            dmitry.rybakov@mongodb.com Dmitry Rybakov
            Reporter:
            alex.bevilacqua@mongodb.com Alex Bevilacqua
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: