diff --git a/lib/ar_lazy_preload/active_record/association.rb b/lib/ar_lazy_preload/active_record/association.rb index fb95a48..a8435ba 100644 --- a/lib/ar_lazy_preload/active_record/association.rb +++ b/lib/ar_lazy_preload/active_record/association.rb @@ -4,7 +4,7 @@ module ArLazyPreload # ActiveRecord::Association patch with a hook for lazy preloading module Association def load_target - owner.try_preload_lazily(reflection.name) + owner.try_preload_lazily(reflection.name) unless owner.auto_preload == false super end end diff --git a/lib/ar_lazy_preload/active_record/base.rb b/lib/ar_lazy_preload/active_record/base.rb index 51888fd..1df911b 100644 --- a/lib/ar_lazy_preload/active_record/base.rb +++ b/lib/ar_lazy_preload/active_record/base.rb @@ -8,7 +8,13 @@ def self.included(base) end attr_accessor :lazy_preload_context + attr_reader :auto_preload delegate :try_preload_lazily, to: :lazy_preload_context, allow_nil: true + + def skip_auto_preload + @auto_preload = false + self + end end end diff --git a/spec/ar_lazy_preload/ar_lazy_preload_spec.rb b/spec/ar_lazy_preload/ar_lazy_preload_spec.rb index c529670..dd49af5 100644 --- a/spec/ar_lazy_preload/ar_lazy_preload_spec.rb +++ b/spec/ar_lazy_preload/ar_lazy_preload_spec.rb @@ -230,4 +230,16 @@ end.to make_database_queries(count: 2) end end + + describe "skip_auto_preload" do + subject { Comment.threads.lazy_preload(:replies) } + + # SELECT "comments".* FROM "comments" + # SELECT "comments".* FROM "comments" WHERE "comments"."parent_comment_id" = ? + it "only load own association" do + expect do + subject.map { |comment| comment.skip_auto_preload.reply_ids } + end.to make_database_queries(matching: '"comments"."parent_comment_id" = ?') + end + end end diff --git a/spec/ar_lazy_preload/auto_preload_spec.rb b/spec/ar_lazy_preload/auto_preload_spec.rb index 123f1fd..4307e88 100644 --- a/spec/ar_lazy_preload/auto_preload_spec.rb +++ b/spec/ar_lazy_preload/auto_preload_spec.rb @@ -10,9 +10,10 @@ let!(:comment1) { create(:comment, user: user1, post: post) } let!(:comment1) { create(:comment, user: user2, post: post) } - before(:all) { ArLazyPreload.config.auto_preload = true } + before(:each) { ArLazyPreload.config.auto_preload = true } describe "auto preloading" do + subject { Comment.all } # SELECT "comments".* FROM "comments" @@ -20,5 +21,13 @@ it "loads association automatically" do expect { subject.each { |comment| comment.user&.id } }.to make_database_queries(count: 2) end + + # SELECT "comments".* FROM "comments" + # SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? + it "only load own association" do + expect do + subject.each { |comment| comment.skip_auto_preload.user&.id } + end.to make_database_queries(matching: '"users"."id" = ?') + end end end