Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4368

Unexpected behaviour using "belongs_to" with "foreign_key"

    • Type: Icon: Bug Bug
    • Resolution: Won't Fix
    • Priority: Icon: Major - P3 Major - P3
    • 12_01_17
    • Affects Version/s: 5.1.4, 5.1.5, 6.0.2
    • Component/s: None
    • Labels:
      None

      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.

            Assignee:
            Unassigned Unassigned
            Reporter:
            sylvain-8422 Sylvain Bernier
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: