diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2017-07-23 16:47:11 -0500 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2017-07-23 16:47:11 -0500 |
commit | 68b5d274a365c1babdb92dedfcf2e600138be5eb (patch) | |
tree | 1ad85544cd7bda1fd8ab5547f37dec2ddf9efc91 | |
parent | f96abd1dfc858ce73afcf54c87ed4e88401a7048 (diff) | |
download | rails-68b5d274a365c1babdb92dedfcf2e600138be5eb.tar.gz rails-68b5d274a365c1babdb92dedfcf2e600138be5eb.tar.bz2 rails-68b5d274a365c1babdb92dedfcf2e600138be5eb.zip |
Add and test preloading scope
-rw-r--r-- | lib/active_storage/attached/macros.rb | 6 | ||||
-rw-r--r-- | test/models/attachments_test.rb | 5 |
2 files changed, 10 insertions, 1 deletions
diff --git a/lib/active_storage/attached/macros.rb b/lib/active_storage/attached/macros.rb index 0452089a5f..5915793f8a 100644 --- a/lib/active_storage/attached/macros.rb +++ b/lib/active_storage/attached/macros.rb @@ -33,6 +33,10 @@ module ActiveStorage::Attached::Macros # There are no columns defined on the model side, Active Storage takes # care of the mapping between your records and the attachments. # + # To avoid N+1 queries, you can include the attached blobs in your query like so: + # + # Gallery.where(user: Current.user).with_attached_photos + # # If the +:dependent+ option isn't set, all the attachments will be purged # (i.e. destroyed) whenever the record is destroyed. def has_many_attached(name, dependent: :purge_later) @@ -44,6 +48,8 @@ module ActiveStorage::Attached::Macros has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment" has_many :"#{name}_blobs", through: :"#{name}_attachments" + scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) } + if dependent == :purge_later before_destroy { public_send(name).purge_later } end diff --git a/test/models/attachments_test.rb b/test/models/attachments_test.rb index 45f62b0bbf..eac3cbe680 100644 --- a/test/models/attachments_test.rb +++ b/test/models/attachments_test.rb @@ -73,7 +73,10 @@ class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" }, { io: StringIO.new("IT"), filename: "country.jpg", content_type: "image/jpg" }) - User.where(id: @user.id).includes(highlights_attachments: :blob).first + highlights = User.where(id: @user.id).with_attached_highlights.first.highlights + + assert_equal "town.jpg", highlights.first.filename.to_s + assert_equal "country.jpg", highlights.second.filename.to_s end test "purge attached blobs" do |