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.
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
Accoring to this rails guide you can do the following:
validates :assignment_date, :uniqueness => { :scope => :name }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With