mongoid uniqueness validation many-to-many relation
I have following association
class Employee
include Mongoid::Document
employee_id :name
references_many :companies, stored_as => :array, :inverse_of => :employees
end
class C开发者_如何学编程ompany
include Mongoid::Document
field :name
references_many :employees, stored_as => :array, :inverse_of => :companies
end
Now How can I check the uniqueness of employee_id
of employee within a single company
Hey Gagan. First, this line in your Employee model needs to be corrected:
employee_id :name
For the validation, you should be able to do this:
class Employee
include Mongoid::Document
field :employee_id, :type => Integer
references_many :companies, :stored_as => :array, :inverse_of => :employees
validates_uniqueness_of :employee_id
end
You can test it easily like this:
>> e = Employee.create :employee_id => 10
=> #
>> Employee.new(:employee_id => 10).valid?
=> false
精彩评论