MONGOID-5759 ensure unpersisted documents are picked up via HasMany#find#6137
MONGOID-5759 ensure unpersisted documents are picked up via HasMany#find#6137jamis merged 1 commit intomongodb:masterfrom
Conversation
There was a problem hiding this comment.
Pull request overview
Fixes HasMany#find with a block so that it searches in-memory (built/unpersisted) associated documents in addition to persisted records, addressing MONGOID-5759.
Changes:
- Add specs verifying
has_many#find { ... }returns built/unpersisted documents when the parent is not persisted. - Update
HasMany::Proxy#findto use in-memory enumeration (detect) when called with only a block.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| spec/mongoid/association/referenced/has_many/proxy_spec.rb | Adds regression coverage for #find with block to include built/unpersisted documents when parent is new. |
| lib/mongoid/association/referenced/has_many/proxy.rb | Adjusts #find behavior for block-only calls to search the association enumerable (including _added docs). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| 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 |
There was a problem hiding this comment.
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.
When using
findwith a block on a has-many association, Mongoid does not include unpersisted documents in the search. This PR fixes that bug.