validates_uniqueness_of由两个字段组成

时间:2012-04-07 11:35:27

标签: ruby mongodb mongoid

我有模特:

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 

如果我对这一行发表评论,一切正常。

2 个答案:

答案 0 :(得分:14)

根据this rails指南,您可以执行以下操作:

validates :assignment_date, :uniqueness => { :scope => :name } 

答案 1 :(得分:14)

Mongoid:

validates_uniqueness_of :name, :scope => :assignment_date

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

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