Validation of the Mongolian many-to-many uniqueness

I have the following association

class Employee
  include Mongoid::Document
  employee_id :name
 references_many :companies, stored_as => :array, :inverse_of => :employees
end

class Company
  include Mongoid::Document
  field :name
 references_many :employees, stored_as => :array, :inverse_of => :companies
end

Now How to check the uniqueness of an employee_idemployee within onecompany

+3
source share
1 answer

Hey Gagan. First, this line in your Employee model should be fixed:

employee_id :name

To check, 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 easily test this:

>> e = Employee.create :employee_id => 10
 => #

>> Employee.new(:employee_id => 10).valid?
 => false
0
source

Source: https://habr.com/ru/post/1763974/


All Articles