-
Type: Task
-
Resolution: Works as Designed
-
Priority: 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:
- Confirm whether the script below matches ActiveRecord's behavior.
- 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.
- related to
-
MONGOID-4815 Add :conditions option example to reference documentation
- Closed