File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -23,3 +23,32 @@ Mongoid behaves slightly differently to Active Record when using ``#valid?``
2323on already persisted data. Active Record's ``#valid?`` will run all
2424validations whereas Mongoid's ``#valid?`` will only run validations on
2525documents that are in memory as an optimization.
26+
27+
28+ ``validates_uniqueness_of`` and ``:conditions`` Option
29+ =======================================================
30+
31+ The ``:conditions`` option to ``validates_uniqueness_of`` can be used to
32+ provide additional conditions to add to the database query looking for
33+ identical documents. This option does not influence when the validation
34+ is executed because it is not considered when Mongoid retrieves the present
35+ value of the respective field from the model. Consider the following example:
36+
37+ .. code-block:: ruby
38+
39+ class Band
40+ include Mongoid::Document
41+
42+ field :name, type: String
43+ field :year, type: Integer
44+
45+ validates_uniqueness_of :name, conditions: -> { where(:year.gte => 2000) }
46+ end
47+
48+ # OK
49+ Band.create!(name: "Sun Project", year: 2000)
50+
51+ # Fails validation because there is a band with the "Sun Project" name
52+ # and year 2000 in the database, even though the model being created now
53+ # does not have a year.
54+ Band.create!(name: "Sun Project")
You can’t perform that action at this time.
0 commit comments