Class: Mongoid::Multitenancy::TenantUniquenessValidator

Inherits:
Validatable::UniquenessValidator
  • Object
show all
Defined in:
lib/mongoid/multitenancy/validators/tenant_uniqueness.rb

Overview

Validates whether or not a field is unique against the documents in the database.

It is also possible to limit the uniqueness constraint to a set of records matching certain conditions:

class Person
  include Mongoid::Document
  include Mongoid::Multitenancy::Document
  field :title
  field :active, type: Boolean
  tenant :client

  validates_tenant_uniqueness_of :title, conditions: -> {where(active: true)}
end

Examples:

Define the tenant uniqueness validator.


class Person
  include Mongoid::Document
  include Mongoid::Multitenancy::Document
  field :title
  tenant :client

  validates_tenant_uniqueness_of :title
end

Instance Method Summary collapse

Instance Method Details

#validate_root(document, attribute, value) ⇒ Object

Validate a tenant root document.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mongoid/multitenancy/validators/tenant_uniqueness.rb', line 30

def validate_root(document, attribute, value)
  klass = document.class

  while klass.superclass.respond_to?(:validators) && klass.superclass.validators.include?(self)
    klass = klass.superclass
  end
  criteria = create_criteria(klass, document, attribute, value)

  # <<Add the tenant Criteria>>
  criteria = with_tenant_criterion(criteria, klass, document)
  # Add additional conditions
  if options[:conditions]
    conditions = klass.unscoped { options[:conditions].call }
    criteria = criteria.merge(conditions)
  end

  if criteria.read(mode: :primary).exists?
    add_error(document, attribute, value)
  end
end

#with_tenant_criterion(criteria, base, document) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Add the scope criteria for a tenant model criteria.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mongoid/multitenancy/validators/tenant_uniqueness.rb', line 54

def with_tenant_criterion(criteria, base, document)
  item = base.tenant_field.to_sym
  name = document.database_field_name(item)
  tenant_value = document.attributes[name]

  if document.class.tenant_options[:optional] && !options[:exclude_shared]
    if tenant_value
      criteria = criteria.where(:"#{item}".in => [tenant_value, nil])
    end
  else
    criteria = criteria.where(item => tenant_value)
  end

  criteria
end