1

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?

Serhiy Nazarov
  • 369
  • 3
  • 8

2 Answers2

1

You can create a method that will be call by a callback.
See documentation for callbacks.

You can simply raise something from this method if your conditions are not respected.

Ask if you need a sample.

jgburet
  • 535
  • 3
  • 15
  • this solution very good for model layer. Thanks! Can I do this on MongoDB layer? I use single db with many services, good idea create index in MongoDB but I don't know as – Serhiy Nazarov Feb 21 '15 at 09:53
  • I didn't understand what you said. – jgburet Feb 21 '15 at 12:35
  • I need create uniqueness index in MongoDB, not in Mongoid – Serhiy Nazarov Feb 23 '15 at 16:01
  • Still not sure of what you mean. Mongoid is a wrapper of MongoDB for your ruby environment. It deals itself with fields creation etc. However, if you want to create an index on a field (for quicker search) in one of your models, you can check this documentation: http://mongoid.org/en/mongoid/docs/indexing.html – jgburet Feb 24 '15 at 16:22
0

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.

liukgg
  • 226
  • 3
  • 6