验证
Mongoid 包括ActiveModel::Validations
以提供基本的验证以及额外的关联和唯一性验证器。
见Active Record Validations 和 ActiveModel::Validations 文档以获取更多信息。
在已经持久化的数据上使用 #valid?
时,Mongoid 的行为与 Active Record 略有不同。Active Record 的 #valid?
会运行所有验证,而 Mongoid 的 #valid?
仅为内存中的文档运行验证,作为优化。
validates_uniqueness_of
和 :conditions
选项
在 validates_uniqueness_of
的 :conditions
选项可以用来提供附加条件,以添加到数据库查询中,以查找相同的文档。此选项不会影响验证何时执行,因为它在 Mongoid 从模型检索相应字段的当前值时不会被考虑。考虑以下示例
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")
使用 validates_uniqueness_of
进行读取偏好校验
为了校验属性的唯一性,Mongoid 必须检查该属性的值在数据库中是否已存在。如果 Mongoid 查询副本集的次要成员,则有可能读取到陈旧的数据。因此,用于校验 validates_uniqueness_of
的查询始终使用读取偏好 primary
。