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

'where' query incorrectly works for belongs_to relations with custom primary_key

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major - P3
    • Resolution: Fixed
    • 7.2.0, 7.0.11, 7.1.6
    • 8.0.1
    • Associations, Query
    • None

    Description

      Setup:

       

      class Company
        include Mongoid::Document
       
        field :legacy_id, type: Integer
       
        has_many :products, inverse_of: :company, primary_key: 'legacy_id', foreign_key: 'company_legacy_id'
      end
       
      class Product
        include Mongoid::Document
       
        field :legacy_id, type: Integer
        field :company_legacy_id, type: Integer
       
        belongs_to :company, inverse_of: :products, primary_key: 'legacy_id', foreign_key: 'company_legacy_id'
      end

       

       

      This works correctly:

      c = Company.create!(legacy_id: 3)
      # => #<Company _id: 60069b5158af1454d9ae1818, legacy_id: 3>
      p = Product.create!(legacy_id: 5, company: c)
      # => #<Product _id: 60069b6658af1454d9ae1819, legacy_id: 5, company_legacy_id: 3>
      

      However this query ignores primary key (AR works correctly in such cases):

      Product.where(company: c)
      # => #<Mongoid::Criteria
      #  selector: {"company_legacy_id"=>BSON::ObjectId('60069b5158af1454d9ae1818')}
      #  options:  {}
      #  class:    Product
      #  embedded: false>
      

      Foreign key is correct, but _id is used as value ignoring custom primary_key.

      Attachments

        Activity

          People

            neil.shweky@mongodb.com Neil Shweky (Inactive)
            shark55555@gmail.com Alexey Ramazanov
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: