Skip to content

Commit 964e9bc

Browse files
authored
MONGOID-5043 fix where query with custom primary key (#5170)
1 parent b2143b3 commit 964e9bc

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

lib/mongoid/fields/foreign_key.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ def evolve(object)
6060
if object_id_field? || object.is_a?(Document)
6161
if association.polymorphic?
6262
association.convert_to_foreign_key(object)
63+
elsif object.is_a?(Document) && object.respond_to?(association.primary_key)
64+
primary_key_field.evolve(object.send(association.primary_key))
6365
else
6466
object.__evolve_object_id__
6567
end
@@ -142,6 +144,11 @@ def related_id_field
142144
@related_id_field ||= association.klass.fields["_id"]
143145
end
144146

147+
def primary_key_field
148+
@primary_key_field ||= association.klass.fields[association.primary_key]
149+
end
150+
151+
145152
# This is used when default values need to be serialized. Most of the
146153
# time just return the object.
147154
#

spec/integration/associations/foreign_key_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@
2727
expect(email.company.id).to eq(company.id)
2828
end
2929

30+
it "has the correct criteria" do
31+
company = ForeignKeySpec::Company.create!(c: "3")
32+
email = ForeignKeySpec::Email.create!(company: company)
33+
34+
criteria = ForeignKeySpec::Email.where(company: company)
35+
36+
expect(criteria.selector).to eq({ "c_ref" => "3" })
37+
end
38+
3039
context 'with default scope' do
3140
context 'using default scope' do
3241
it 'looks up child' do

0 commit comments

Comments
 (0)