Skip to content

Commit 373c01c

Browse files
committed
Using cache when within a transaction if already loaded
1 parent 8fdb3d3 commit 373c01c

File tree

3 files changed

+18
-11
lines changed

3 files changed

+18
-11
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# IdentityCache changelog
22

3+
- Fix: Allow use of pre-loaded cache from within a transaction
4+
35
#### 0.4.0
46

57
- Return an array from fetched association to prevent chaining. Up to now, a relation was returned by default. (#287)

lib/identity_cache/belongs_to_caching.rb

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,19 @@ def build_normalized_belongs_to_cache(association, options)
3535
self.class_eval(<<-CODE, __FILE__, __LINE__ + 1)
3636
def #{options[:cached_accessor_name]}
3737
association_klass = association(:#{association}).klass
38-
if association_klass.should_use_cache? && #{foreign_key}.present? && !association(:#{association}).loaded?
39-
if instance_variable_defined?(:@#{options[:records_variable_name]})
40-
@#{options[:records_variable_name]}
41-
else
42-
@#{options[:records_variable_name]} = association_klass.fetch_by_id(#{foreign_key})
43-
end
44-
else
45-
if IdentityCache.fetch_read_only_records && association_klass.should_use_cache?
38+
39+
if !#{foreign_key}.present? || association(:#{association}).loaded?
40+
if IdentityCache.fetch_read_only_records
4641
readonly_copy(association(:#{association}).load_target)
4742
else
4843
#{association}
4944
end
45+
elsif instance_variable_defined?(:@#{options[:records_variable_name]})
46+
@#{options[:records_variable_name]}
47+
elsif association_klass.should_use_cache?
48+
@#{options[:records_variable_name]} = association_klass.fetch_by_id(#{foreign_key})
49+
else
50+
#{association}
5051
end
5152
end
5253

lib/identity_cache/configuration_dsl.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,10 +234,14 @@ def #{options[:cached_ids_name]}
234234
235235
def #{options[:cached_accessor_name]}
236236
association_klass = association(:#{association}).klass
237-
if association_klass.should_use_cache? && !#{association}.loaded?
238-
@#{options[:records_variable_name]} ||= #{options[:association_reflection].klass}.fetch_multi(#{options[:cached_ids_name]})
239-
else
237+
if #{association}.loaded?
240238
#{association}.to_a
239+
elsif instance_variable_defined?(:@#{options[:records_variable_name]})
240+
@#{options[:records_variable_name]}
241+
elsif association_klass.should_use_cache?
242+
@#{options[:records_variable_name]} = #{options[:association_reflection].klass}.fetch_multi(#{options[:cached_ids_name]})
243+
else
244+
#{association}.to_a
241245
end
242246
end
243247

0 commit comments

Comments
 (0)