Skip to content

Commit

Permalink
Merge pull request #104 from OuYangJinTing/Fix-preloader
Browse files Browse the repository at this point in the history
Fix: preloader if exists default scope
  • Loading branch information
hooopo authored Apr 20, 2020
2 parents edeb6d3 + 72c8b8e commit f4ea950
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/second_level_cache/active_record/preloader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module Preloader
def records_for(ids, &block)
return super unless klass.second_level_cache_enabled?
return super unless reflection.is_a?(::ActiveRecord::Reflection::BelongsToReflection)
return super if klass.default_scopes.present?

map_cache_keys = ids.map { |id| klass.second_level_cache_key(id) }
records_from_cache = ::SecondLevelCache.cache_store.read_multi(*map_cache_keys)
Expand Down
3 changes: 3 additions & 0 deletions test/model/book.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
t.decimal :discount_percentage, precision: 5, scale: 2
t.integer :images_count, default: 0
t.date :publish_date
t.boolean :normal, default: true, nil: false
end

class Book < ActiveRecord::Base
second_level_cache

default_scope -> { where(normal: true) }

belongs_to :user, counter_cache: true
has_many :images, as: :imagable
end
10 changes: 10 additions & 0 deletions test/preloader_belongs_to_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,14 @@ def test_preloader_caches_includes_tried_set_inverse_instance
accounts = Account.includes(:user)
assert_equal accounts.first.object_id, accounts.first.user.account.object_id
end

def test_preloader_from_db_when_exists_scope
user = User.create
book = user.books.create
image = book.images.create
book.toggle!(:normal)
assert_queries(:any) do
assert_nil Image.includes(:imagable).where(id: image.id).first.imagable
end
end
end

0 comments on commit f4ea950

Please sign in to comment.