Module: MultiTenantFindBy

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

Instance Method Summary collapse

Instance Method Details

#cached_find_by_statement(key, &block) ⇒ Object



384
385
386
387
388
389
# File 'lib/activerecord-multi-tenant/query_rewriter.rb', line 384

def cached_find_by_statement(key, &block)
  return super unless respond_to?(:scoped_by_tenant?) && scoped_by_tenant?

  key = Array.wrap(key) + [MultiTenant.current_tenant_id.to_s]
  super(key, &block)
end

#find(*ids) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/activerecord-multi-tenant/query_rewriter.rb', line 355

def find(*ids)
  return super unless respond_to?(:scoped_by_tenant?) && scoped_by_tenant?

  # This duplicates a bunch of code from AR's find() method
  return super unless ids.length == 1
  return super if ids.first.kind_of?(Symbol)
  return super if block_given? ||
                  primary_key.nil? ||
                  default_scopes.any? ||
                  current_scope ||
                  columns_hash.include?(inheritance_column) ||
                  ids.first.kind_of?(Array)

  id = ids.first
    if ActiveRecord::Base === id
      id = id.id
      ActiveSupport::Deprecation.warn(<<-MSG.squish)
        You are passing an instance of ActiveRecord::Base to `find`.
        Please pass the id of the object by calling `.id`
      MSG
    end
  key = primary_key

  # Ensure we never use the cached version
  find_by_statement_cache.synchronize { find_by_statement_cache[key] = nil }

  super
end

#find_by(*args) ⇒ Object

Disable caching for find and find_by in Rails 4.2 - we don’t have a good way to prevent caching problems here when prepared statements are enabled



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/activerecord-multi-tenant/query_rewriter.rb', line 335

def find_by(*args)
  return super unless respond_to?(:scoped_by_tenant?) && scoped_by_tenant?

  # This duplicates a bunch of code from AR's find() method
  return super if current_scope || !(Hash === args.first) || reflect_on_all_aggregations.any?
  return super if default_scopes.any?

  hash = args.first

  return super if hash.values.any? { |v| v.nil? || Array === v || Hash === v }
  return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) }

  key = hash.keys

  # Ensure we never use the cached version
  find_by_statement_cache.synchronize { find_by_statement_cache[key] = nil }

  super
end