Module: SecondLevelCache::ActiveRecord::Associations::HasOneAssociation

Defined in:
lib/second_level_cache/active_record/has_one_association.rb

Instance Method Summary collapse

Instance Method Details

#find_targetObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/second_level_cache/active_record/has_one_association.rb', line 7

def find_target
  return super unless klass.second_level_cache_enabled?
  return super if klass.default_scopes.present? || reflection.scope
  # TODO: implement cache with has_one scope

  through = reflection.options[:through]
  record  = if through
    return super unless owner.class.reflections[through.to_s].klass.second_level_cache_enabled?
    begin
      reflection.klass.find(owner.send(through).read_attribute(reflection.foreign_key))
    rescue StandardError
      nil
    end
  else
    uniq_keys = { reflection.foreign_key => owner[reflection.active_record_primary_key] }
    uniq_keys[reflection.type] = owner.class.base_class.name if reflection.options[:as]
    klass.fetch_by_uniq_keys(uniq_keys)
  end

  return nil unless record
  record.tap { |r| set_inverse_instance(r) }
end