Skip to content

Commit 09f30b7

Browse files
p-mongop
andauthored
Fix MONGOID-4815 Add :conditions option example to reference documentation (#5329)
Co-authored-by: Oleg Pudeyev <[email protected]>
1 parent bbcbd0b commit 09f30b7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

docs/reference/validation.txt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,32 @@ Mongoid behaves slightly differently to Active Record when using ``#valid?``
2323
on already persisted data. Active Record's ``#valid?`` will run all
2424
validations whereas Mongoid's ``#valid?`` will only run validations on
2525
documents 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")

0 commit comments

Comments
 (0)