Class: Mongoid::Multitenancy::TenancyValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mongoid/multitenancy/validators/tenancy.rb

Overview

Validates whether or not a tenant field is correct.

Examples:

Define the tenant validator


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

  validates_tenancy_of :client
end

Instance Method Summary collapse

Instance Method Details

#validate_each(object, attribute, value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mongoid/multitenancy/validators/tenancy.rb', line 16

def validate_each(object, attribute, value)
  # Immutable Check
  if options[:immutable]
    if object.send(:attribute_changed?, attribute) && object.send(:attribute_was, attribute)
      object.errors.add(attribute, 'is immutable and cannot be updated')
    end
  end

  # Ownership check
  if value && Mongoid::Multitenancy.current_tenant && value != Mongoid::Multitenancy.current_tenant.id
    object.errors.add(attribute, 'not authorized')
  end

  # Optional Check
  if !options[:optional] && value.nil?
    object.errors.add(attribute, 'is mandatory')
  end
end