Skip to content

Commit

Permalink
MONGOID-5149 Skip inverse detection when inverse_of: nil is set (#5027)
Browse files Browse the repository at this point in the history
* Skipping inverse relation detection when inverse_of: nil is set

* Extracting a specific spec for the matter at hand
  • Loading branch information
simonc committed Aug 23, 2021
1 parent a4a614b commit f273227
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/mongoid/association/relatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ def bindable?(doc); false; end
# @since 7.0
def inverses(other = nil)
return [ inverse_of ] if inverse_of
return [] if @options.key?(:inverse_of) && !inverse_of

if polymorphic?
polymorphic_inverses(other)
else
Expand Down
20 changes: 20 additions & 0 deletions spec/mongoid/association/referenced/belongs_to_query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,24 @@
expect(school.team).to eq('Bulldogs')
end
end

context 'when projecting with #only while having similar inverse_of candidates' do
before do
alice = HmmOwner.create!(name: 'Alice')
bob = HmmOwner.create!(name: 'Bob')

HmmPet.create!(name: 'Rex', current_owner: bob, previous_owner: alice)
end

let(:pet) { HmmPet.where(name: 'Rex').only(:name, :previous_owner_id, 'previous_owner.name').first }

it 'populates specified fields' do
expect(pet.name).to eq('Rex')
expect(pet.previous_owner.name).to eq('Alice')
end

it 'does not try to load the inverse for an association that explicitly prevents it' do
expect { pet.previous_owner.name }.not_to raise_error
end
end
end
17 changes: 17 additions & 0 deletions spec/mongoid/association/referenced/has_many_models.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,23 @@ class HmmAddress
belongs_to :company, class_name: 'HmmCompany'
end

class HmmOwner
include Mongoid::Document

has_many :pets, class_name: 'HmmPet', inverse_of: :current_owner

field :name, type: String
end

class HmmPet
include Mongoid::Document

belongs_to :current_owner, class_name: 'HmmOwner', inverse_of: :pets, optional: true
belongs_to :previous_owner, class_name: 'HmmOwner', inverse_of: nil, optional: true

field :name, type: String
end

class HmmSchool
include Mongoid::Document

Expand Down

0 comments on commit f273227

Please sign in to comment.