Details
-
Bug
-
Resolution: Won't Fix
-
Major - P3
-
5.1.4, 5.1.5, 6.0.2
-
None
-
None
Description
Here is some unusual code that behaves unexpectedly :
class King
|
include Mongoid::Document
|
end
|
|
class Peasant
|
include Mongoid::Document
|
|
belongs_to :king
|
end
|
|
class Harvest
|
include Mongoid::Document
|
|
belongs_to :peasant, foreign_key: 'king_id'
|
end
|
|
RSpec.describe do
|
let(:king) { King.create! }
|
let(:peasant) { Peasant.create!(king: king) }
|
|
before { Harvest.create!(peasant: peasant) }
|
|
it { expect(peasant.king_id).to be == king.id }
|
|
it { expect(peasant.king).to be == king }
|
end
|
The first test (king_id == king.id) will pass, but the second one (king == king) will fail :
Failures:
|
|
1) should be == #<King:0x007fa21d378d10>
|
Failure/Error: it { expect(peasant.king).to be == king }
|
expected: == #<King _id: 581b92adcf6bf320795fcd68, >
|
got: #<Harvest _id: 581b92adcf6bf320795fcd6a, king_id: BSON::ObjectId('581b92adcf6bf320795fcd69')>
|
I am aware that the part asking for foreign_key: 'king_id' is a bit weird, but we need to do this in our current refactoring.
We are using 5.1.4/5, but I have tested 6.0.2 and the issue is also there.
I have done a bit of tracing, and the king field is overwritten when executing the Harvest.create!, in #set_relation, in mongoid/relations/accessors.rb.