Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validates_uniqueness_of by two fields

I have the model:

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 ]

But when I'm trying to insert the 2 different document with the same name, but different assigned_date I get the error:

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

I have tryed both versions:

  validates_uniqueness_of [ :name, :assignment_date ]

and

  validates_uniqueness_of :name, :assignment_date 

If I'll comment this line all works fine.

like image 602
ceth Avatar asked Apr 07 '12 11:04

ceth


2 Answers

Mongoid:

validates_uniqueness_of :name, :scope => :assignment_date

From the docs: Note that for embedded documents, this will only check that the field is unique within the context of the parent document, not the entire database.

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

like image 168
joelparkerhenderson Avatar answered Oct 23 '22 23:10

joelparkerhenderson


Accoring to this rails guide you can do the following:

validates :assignment_date, :uniqueness => { :scope => :name } 
like image 45
Vapire Avatar answered Oct 23 '22 22:10

Vapire