diff --git a/CHANGELOG.md b/CHANGELOG.md index a0eb3936..b6ce541a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # IdentityCache changelog +- Fix: Allow use of pre-loaded cache from within a transaction + #### 0.4.0 - Return an array from fetched association to prevent chaining. Up to now, a relation was returned by default. (#287) diff --git a/lib/identity_cache/belongs_to_caching.rb b/lib/identity_cache/belongs_to_caching.rb index 2dc31da8..6b4ef8aa 100644 --- a/lib/identity_cache/belongs_to_caching.rb +++ b/lib/identity_cache/belongs_to_caching.rb @@ -35,18 +35,19 @@ def build_normalized_belongs_to_cache(association, options) self.class_eval(<<-CODE, __FILE__, __LINE__ + 1) def #{options[:cached_accessor_name]} association_klass = association(:#{association}).klass - if association_klass.should_use_cache? && #{foreign_key}.present? && !association(:#{association}).loaded? - if instance_variable_defined?(:@#{options[:records_variable_name]}) - @#{options[:records_variable_name]} - else - @#{options[:records_variable_name]} = association_klass.fetch_by_id(#{foreign_key}) - end - else - if IdentityCache.fetch_read_only_records && association_klass.should_use_cache? + + if !#{foreign_key}.present? || association(:#{association}).loaded? + if IdentityCache.fetch_read_only_records readonly_copy(association(:#{association}).load_target) else #{association} end + elsif instance_variable_defined?(:@#{options[:records_variable_name]}) + @#{options[:records_variable_name]} + elsif association_klass.should_use_cache? + @#{options[:records_variable_name]} = association_klass.fetch_by_id(#{foreign_key}) + else + #{association} end end diff --git a/lib/identity_cache/configuration_dsl.rb b/lib/identity_cache/configuration_dsl.rb index 7da09903..a297b21a 100644 --- a/lib/identity_cache/configuration_dsl.rb +++ b/lib/identity_cache/configuration_dsl.rb @@ -234,10 +234,14 @@ def #{options[:cached_ids_name]} def #{options[:cached_accessor_name]} association_klass = association(:#{association}).klass - if association_klass.should_use_cache? && !#{association}.loaded? - @#{options[:records_variable_name]} ||= #{options[:association_reflection].klass}.fetch_multi(#{options[:cached_ids_name]}) - else + if #{association}.loaded? #{association}.to_a + elsif instance_variable_defined?(:@#{options[:records_variable_name]}) + @#{options[:records_variable_name]} + elsif association_klass.should_use_cache? + @#{options[:records_variable_name]} = #{options[:association_reflection].klass}.fetch_multi(#{options[:cached_ids_name]}) + else + #{association}.to_a end end