aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/attached
diff options
context:
space:
mode:
authorYoshiyuki Hirano <yhirano@me.com>2017-09-17 18:24:16 +0900
committerYoshiyuki Hirano <yhirano@me.com>2017-09-19 06:02:00 +0900
commit704bf9b9c64a2f92c6e72d74350bd8f00aaca5c5 (patch)
tree55807438551878c881d32363bfb980ef9e17ffe7 /activestorage/lib/active_storage/attached
parent37be1cb47755a3d0a02eed12ac8cfb377b172f2d (diff)
downloadrails-704bf9b9c64a2f92c6e72d74350bd8f00aaca5c5.tar.gz
rails-704bf9b9c64a2f92c6e72d74350bd8f00aaca5c5.tar.bz2
rails-704bf9b9c64a2f92c6e72d74350bd8f00aaca5c5.zip
Add `with_attached_*` scope to `has_one_attached` macro
* For avoiding N+1 problem, added `with_attached_*` scope to `has_one_attached` macro.
Diffstat (limited to 'activestorage/lib/active_storage/attached')
-rw-r--r--activestorage/lib/active_storage/attached/macros.rb6
1 files changed, 6 insertions, 0 deletions
diff --git a/activestorage/lib/active_storage/attached/macros.rb b/activestorage/lib/active_storage/attached/macros.rb
index 35a081adc4..f0256718ac 100644
--- a/activestorage/lib/active_storage/attached/macros.rb
+++ b/activestorage/lib/active_storage/attached/macros.rb
@@ -12,6 +12,10 @@ module ActiveStorage
# There is no column defined on the model side, Active Storage takes
# care of the mapping between your records and the attachment.
#
+ # To avoid N+1 queries, you can include the attached blobs in your query like so:
+ #
+ # User.with_attached_avatar
+ #
# Under the covers, this relationship is implemented as a +has_one+ association to a
# ActiveStorage::Attachment record and a +has_one-through+ association to a
# ActiveStorage::Blob record. These associations are available as +avatar_attachment+
@@ -33,6 +37,8 @@ module ActiveStorage
has_one :"#{name}_attachment", -> { where(name: name) }, class_name: "ActiveStorage::Attachment", as: :record
has_one :"#{name}_blob", through: :"#{name}_attachment", class_name: "ActiveStorage::Blob", source: :blob
+ scope :"with_attached_#{name}", -> { includes("#{name}_attachment": :blob) }
+
if dependent == :purge_later
before_destroy { public_send(name).purge_later }
end