mongodb/mongoid

View on GitHub
docs/reference/validation.txt

Summary

Maintainability
Test Coverage
**********
Validation
**********

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 2
   :class: singlecol

Mongoid includes ``ActiveModel::Validations`` to supply the basic
validation plus an additional associated and uniqueness validator.

See the `Active Record Validations
<https://guides.rubyonrails.org/active_record_validations.html>`_
Rails guide and `ActiveModel::Validations
<https://api.rubyonrails.org/classes/ActiveModel/Validations.html>`_
documentation for more information.

Mongoid behaves slightly differently to Active Record when using ``#valid?``
on already persisted data. Active Record's ``#valid?`` will run all
validations whereas Mongoid's ``#valid?`` will only run validations on
documents that are in memory as an optimization.


``validates_uniqueness_of`` and ``:conditions``  Option
=======================================================

The ``:conditions`` option to ``validates_uniqueness_of`` can be used to
provide additional conditions to add to the database query looking for
identical documents. This option does not influence when the validation
is executed because it is not considered when Mongoid retrieves the present
value of the respective field from the model. Consider the following example:

.. code-block:: ruby

  class Band
    include Mongoid::Document

    field :name, type: String
    field :year, type: Integer

    validates_uniqueness_of :name, conditions: -> { where(:year.gte => 2000) }
  end

  # OK
  Band.create!(name: "Sun Project", year: 2000)

  # Fails validation because there is a band with the "Sun Project" name
  # and year 2000 in the database, even though the model being created now
  # does not have a year.
  Band.create!(name: "Sun Project")


Read preference with ``validates_uniqueness_of``
================================================

In order to validate the uniqueness of an attribute, Mongoid must check that
the value for that attribute does not already exist in the database. If Mongoid
queries a secondary member of the replica set, there is a possibility that it
is reading stale data. Because of this, the queries used to check a
``validates_uniqueness_of`` validation always use read preference ``primary``.