Skip to content

Commit dc9d4c2

Browse files
simoncp
authored andcommitted
MONGOID-5149 Skip inverse detection when inverse_of: nil is set (#5027)
* Skipping inverse relation detection when inverse_of: nil is set * Extracting a specific spec for the matter at hand
1 parent f70b05d commit dc9d4c2

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

lib/mongoid/association/relatable.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,8 @@ def bindable?(doc); false; end
122122
# @since 7.0
123123
def inverses(other = nil)
124124
return [ inverse_of ] if inverse_of
125+
return [] if @options.key?(:inverse_of) && !inverse_of
126+
125127
if polymorphic?
126128
polymorphic_inverses(other)
127129
else

spec/mongoid/association/referenced/belongs_to_query_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,24 @@
3535
expect(school.team).to eq('Bulldogs')
3636
end
3737
end
38+
39+
context 'when projecting with #only while having similar inverse_of candidates' do
40+
before do
41+
alice = HmmOwner.create!(name: 'Alice')
42+
bob = HmmOwner.create!(name: 'Bob')
43+
44+
HmmPet.create!(name: 'Rex', current_owner: bob, previous_owner: alice)
45+
end
46+
47+
let(:pet) { HmmPet.where(name: 'Rex').only(:name, :previous_owner_id, 'previous_owner.name').first }
48+
49+
it 'populates specified fields' do
50+
expect(pet.name).to eq('Rex')
51+
expect(pet.previous_owner.name).to eq('Alice')
52+
end
53+
54+
it 'does not try to load the inverse for an association that explicitly prevents it' do
55+
expect { pet.previous_owner.name }.not_to raise_error
56+
end
57+
end
3858
end

spec/mongoid/association/referenced/has_many_models.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,23 @@ class HmmAddress
2424
belongs_to :company, class_name: 'HmmCompany'
2525
end
2626

27+
class HmmOwner
28+
include Mongoid::Document
29+
30+
has_many :pets, class_name: 'HmmPet', inverse_of: :current_owner
31+
32+
field :name, type: String
33+
end
34+
35+
class HmmPet
36+
include Mongoid::Document
37+
38+
belongs_to :current_owner, class_name: 'HmmOwner', inverse_of: :pets, optional: true
39+
belongs_to :previous_owner, class_name: 'HmmOwner', inverse_of: nil, optional: true
40+
41+
field :name, type: String
42+
end
43+
2744
class HmmSchool
2845
include Mongoid::Document
2946

0 commit comments

Comments
 (0)