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

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

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 8.0.1
    • Affects Version/s: 7.2.0, 7.0.11, 7.1.6
    • Component/s: Associations, Query
    • Labels:
      None

      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.

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

              Created:
              Updated:
              Resolved: