Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions lib/mongoid/association/referenced/has_many/proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,14 @@ def exists?(id_or_conditions = :none)
# @yield [ Object ] Yields each enumerable element to the block.
#
# @return [ Document | Array<Document> | nil ] A document or matching documents.
def find(...)
matching = criteria.find(...)
Array(matching).each { |doc| _target.push(doc) }
matching
def find(*args, &block)
if block_given? && args.empty?
detect(&block)
else
matching = criteria.find(*args, &block)
Array(matching).each { |doc| _target.push(doc) }
matching
end
Comment on lines +262 to +269
Copy link

Copilot AI Apr 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proxy#find handles the common find { ... } case by calling detect, which makes built/unpersisted documents visible. However, Mongoid::Criteria#find (and Ruby's Enumerable#find) also support the optional ifnone Proc argument (find(-> { default }) { ... }). With the current condition (block_given? && args.empty?), that form still delegates to criteria.find and will continue to ignore built/unpersisted documents. Consider matching the same empty_or_proc logic as Mongoid::Findable#find / Criteria#find and calling detect(*args, &block) when a block is given and args are empty or a single Proc.

Copilot uses AI. Check for mistakes.
end

# Removes all associations between the base document and the target
Expand Down
17 changes: 17 additions & 0 deletions spec/mongoid/association/referenced/has_many/proxy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2246,6 +2246,23 @@ def with_transaction_via(model, &block)
end
).to be_nil
end

context 'when the parent is not persisted (MONGOID-5759)' do
let(:person) { Person.new }
let!(:post) { person.posts.build(title: 'unpersisted post') }

it 'yields unpersisted built documents' do
expect(
person.posts.find { |p| p.title == 'unpersisted post' }
).to eq(post)
end

it 'returns nil when no match among unpersisted documents' do
expect(
person.posts.find { |p| p.title == 'other' }
).to be_nil
end
end
end
end

Expand Down
Loading