Module: SupportTableCache::Associations::ClassMethods

Defined in:
lib/support_table_cache/associations.rb

Instance Method Summary collapse

Instance Method Details

#cache_belongs_to(association_name) ⇒ void

This method returns an undefined value.

Specify that a belongs_to association should use the cache. This will override the reader method for the association so that it queries from the cache. The association must already be defined.

If you need cached associations to be cleared when data changes, then the associated class will need to include SupportTableCache and cache by the primary key for the association.

Parameters:

  • association_name (Symbol, String)

    The association name to cache.

Raises:

  • ArgumentError if the association is not defined or if it has a runtime scope.



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/support_table_cache/associations.rb', line 18

def cache_belongs_to(association_name)
  reflection = reflections[association_name.to_s]

  unless reflection&.belongs_to?
    raise ArgumentError.new("The belongs_to #{association_name} association is not defined")
  end

  if reflection.scopes.present?
    raise ArgumentError.new("Cannot cache belongs_to #{association_name} association because it has a scope")
  end

  define_belongs_to_with_cache(association_name.to_s)
end