Search code examples
ruby-on-railsmongoidvalidates-uniqueness-of

MongoId combined uniqueness index


I have three models

class Org
  include Mongoid::Document
  field :name, type: String
  embeds_many :org_groups
end

class OrgGroup
  include Mongoid::Document
  field :name, type: String
  embedded_in :org
  has_and_belongs_to_many :humans
end

class Human
  include Mongoid::Document
  field :name, type: String
end

One Human can be in many Org, but only in one OrgGroup.

I need set uniqueness index for Human in Org.

How I can do this?


Solution

  • If you need a unique index in the mongodb, you can do like this:

    class Person
      include Mongoid::Document
      field :first_name
      field :last_name
    
      index({ first_name: 1, last_name: 1 }, { unique: true })
    end
    

    And the docs are here:

    https://docs.mongodb.com/ecosystem/tutorial/mongoid-indexes/

    Hope this is helpful for you.