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

Querying unscoped associations ignores primary_key/foreign_key depending on association

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 7.1.0.rc0, 7.0.3
    • Affects Version/s: 7.0.2, 6.4.2
    • Component/s: Associations
    • Labels:
      None

      The primary_key and foreign_key are not respected when using unscoped for some reason.

      https://github.com/mongodb/mongoid/blob/621294b9d4f38e2f0a32984bbb415d544bed437c/lib/mongoid/association/referenced/has_and_belongs_to_many/proxy.rb#L200

      https://github.com/mongodb/mongoid/blob/7.0.0-stable/lib/mongoid/association/referenced/has_many/proxy.rb#L306

      Example:

      When I use this query, it correctly generates the criteria.

      @company.emails
      
      #<Mongoid::Criteria
        selector: {"h"=>false, "d"=>"cacheventures.com"}
        options:  {}
        class:    Crawler::Email
        embedded: false>
      

      However, when I use this query, it incorrectly generates the criteria 

      @company.emails.unscoped
      
      <Mongoid::Criteria
        selector: {"d"=>"5b90592edf119da720bba8cc"}
        options:  {}
        class:    Crawler::Email
        embedded: false>
      

      Below is an example of my models

      class Company
          include Mongoid::Document
      
          has_many :emails, primary_key: :w, foreign_key: :d, class_name: 'Crawler::Email'
         
          field :w, as: :website, type: String
      
      end
      
      class Email
          include Mongoid::Document
      
          belongs_to :company, primary_key: :w, foreign_key: :d, class_name: 'Crawler::Company'
      
          field :d, as: :domain, type: String
          field :h, as: :hidden, type: Boolean, default: false
      
          default_scope -> { where(hidden: false) }
      end
      

       

       

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            jarrett Jarrett Lusso
            Votes:
            2 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: