开发者

mongoid uniqueness validation many-to-many relation

开发者 https://www.devze.com 2023-01-15 05:26 出处:网络
I have following association class Employee include Mongoid::Document employee_id :name references_many :companies, stored_as => :array, :inverse_of => :employees

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号