Module: ActiveRecord::Associations::ClassMethods

Defined in:
lib/activerecord-multi-tenant/habtm.rb

Instance Method Summary collapse

Instance Method Details

#has_and_belongs_to_many_with_tenant(name, scope = nil, **options, &extension) ⇒ Object Also known as: has_and_belongs_to_many

rubocop:disable Naming/PredicateName



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/activerecord-multi-tenant/habtm.rb', line 11

def has_and_belongs_to_many_with_tenant(name, scope = nil, **options, &extension)
  # rubocop:enable Naming/PredicateName
  has_and_belongs_to_many_without_tenant(name, scope, **options, &extension)

  middle_reflection = _reflections[name.to_s].through_reflection
  join_model = middle_reflection.klass

  # get tenant_enabled from options and if it is not set, set it to false
  tenant_enabled = options[:tenant_enabled] || false

  return unless tenant_enabled

  tenant_class_name = options[:tenant_class_name]
  tenant_column = options[:tenant_column]

  match = tenant_column.match(/(\w+)_id/)
  tenant_field_name = match ? match[1] : 'tenant'

  join_model.class_eval do
    belongs_to tenant_field_name.to_sym, class_name: tenant_class_name
    before_create :tenant_set

    private

    # This method sets the tenant_id on the join table and executes before creation of the join table record.
    define_method :tenant_set do
      if tenant_enabled
        raise MultiTenant::MissingTenantError, 'Tenant Id is not set' unless MultiTenant.current_tenant_id

        send("#{tenant_column}=", MultiTenant.current_tenant_id)
      end
    end
  end
end