6

我有模型:

class Action
  include Mongoid::Document
  field :name, type: String
  field :assignment_date, type: Date
  ...

  index(
    [
      [ :name, Mongo::ASCENDING ],
      [ :assignment_date, Mongo::ASCENDING ]
      ], 
      unique: true
  )

  validates_uniqueness_of [ :name, :assignment_date ]

但是,当我尝试插入具有相同名称但不同assigned_date 的2个不同文档时,我收到错误消息:

Mongoid::Errors::Validations - Validation failed - Name is already taken, Assignment date is already taken.:

我尝试了两个版本:

  validates_uniqueness_of [ :name, :assignment_date ]

  validates_uniqueness_of :name, :assignment_date 

如果我评论这条线一切正常。

4

2 回答 2

15

蒙古族:

validates_uniqueness_of :name, :scope => :assignment_date

来自文档:请注意,对于嵌入式文档,这只会检查该字段在父文档的上下文中是否唯一,而不是整个数据库。

http://mongoid.org/docs/validation.html

于 2012-04-07T12:04:50.957 回答
14

根据导轨指南,您可以执行以下操作:

validates :assignment_date, :uniqueness => { :scope => :name } 
于 2012-04-07T11:40:53.300 回答