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

Investigate and fix behavior of validates_uniqueness_of :conditions option

    • Type: Icon: Task Task
    • Resolution: Works as Designed
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: None
    • None

      This ticket is a follow-up to MONGOID-4815.

      Based on the comments, it seems that validates_uniqueness_of :conditions option is:

      • Inconsistent with how ActiveRecord behaves
      • Inconsistent with expected MongoDB user behavior.
        • Intuitively, one would expect the validation to mirror a MongoDB `index` with `$unique: true` and `$partialFilterExpression` set, however it does not.

      Let's proceed as follows:

      1. Confirm whether the script below matches ActiveRecord's behavior.
      2. If not matching AR, fix Mongoid's code to match AR.

       

      class Band
        include Mongoid::Document
        
        field :name, type: String
        field :year, type: Integer
        
        validates_uniqueness_of :name, conditions: -> { where(:year.gte => 2000) }
      end
       
      band1 = Band.create!(name: "Sun Project") # OK
      band2 = Band.create!(name: "Sun Project", year: 1998) # OK
      band3 = Band.create!(name: "Sun Project", year: 1998) # OK
      band4 = Band.create!(name: "Sun Project", year: 2000) # OK
      Band.create!(name: "Sun Project") # Fails!
      Band.create!(name: "Sun Project", year: 1998) # Fails!
      Band.create!(name: "Sun Project", year: 2000) # Fails!
      

      Explanation: Once we've created one Band with year >= 2000, we can no longer create a Band with that name of any year or without a year. This leads to a strange/inexplicable state of documents in the DB; any Band that "happened" to be created before band4 stays, while attempting to create the same band afterward is no longer allowed. Since uniqueness validations are used to enforce consistency in the DB, I can't imagine a practical use case for this.

            Assignee:
            jamis.buck@mongodb.com Jamis Buck
            Reporter:
            shields@tablecheck.com Johnny Shields
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: