module MongoModel::DocumentExtensions::Validations::ClassMethods
Public Instance Methods
Creates an object just like Document.create
but calls save! instead of save so an exception is raised if the document is invalid.
# File lib/mongomodel/document/validations.rb, line 17 def create!(attributes={}, &block) if attributes.is_a?(Array) attributes.map { |attrs| create!(attrs, &block) } else object = new(attributes, &block) object.save! object end end
Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user can be named “davidhh”.
class Person < MongoModel::Document validates_uniqueness_of :user_name, :scope => :account_id end
It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.
class TeacherSchedule < MongoModel::Document validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id] end
When the document is created, a check is performed to make sure that no document exists in the database with the given value for the specified attribute (that maps to a property). When the document is updated, the same check is made but disregarding the document itself.
Configuration
options:
-
:message
- Specifies a custom error message (default is: “has already been taken”). -
:scope
- One or more properties by which to limit the scope of the uniqueness constraint. -
:case_sensitive
- Looks for an exact match. Ignored by non-text columns (true
by default). -
:index
- If set to false, disables the unique index constraint (default istrue
). -
:allow_nil
- If set to true, skips this validation if the attribute isnil
(default isfalse
). -
:allow_blank
- If set to true, skips this validation if the attribute is blank (default isfalse
). -
:if
- Specifies a method, proc or string to call to determine if the validation should occur (e.g.:if => :allow_validation
, or:if => Proc.new { |user| user.signup_step > 2 }
). The method, proc or string should return or evaluate to a true or false value. -
:unless
- Specifies a method, proc or string to call to determine if the validation should not occur (e.g.:unless => :skip_validation
, or:unless => Proc.new { |user| user.signup_step <= 2 }
). The method, proc or string should return or evaluate to a true or false value.
Concurrency and integrity¶ ↑
Note that this validation method does not have the same race condition suffered by ActiveRecord and other ORMs. A unique index is added to the collection to ensure that the collection never ends up in an invalid state.
# File lib/mongomodel/document/validations/uniqueness.rb, line 109 def validates_uniqueness_of(*attr_names) validates_with UniquenessValidator, _merge_attributes(attr_names) end