New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add `with_attached_*` scope to `has_one_attached` macro #30629

Merged
merged 1 commit into from Sep 20, 2017
Jump to file or symbol
Failed to load files and symbols.
+19 −0
Diff settings

Always

Just for now

@@ -12,6 +12,10 @@ module Attached::Macros
# 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 @@ def #{name}
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
@@ -84,6 +84,19 @@ class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase
end
end
test "find with attached blob" do
records = %w[alice bob].map do |name|
User.create!(name: name).tap do |user|
user.avatar.attach create_blob(filename: "#{name}.jpg")
end
end
users = User.where(id: records.map(&:id)).with_attached_avatar.all
assert_equal "alice.jpg", users.first.avatar.filename.to_s
assert_equal "bob.jpg", users.second.avatar.filename.to_s
end
test "attach existing blobs" do
@user.highlights.attach create_blob(filename: "funky.jpg"), create_blob(filename: "wonky.jpg")
ProTip! Use n and p to navigate between commits in a pull request.