Skip to content
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

MONGOID-5149 Skip inverse detection when inverse_of: nil is set #5027

Merged
merged 2 commits into from
Aug 23, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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