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

Polymorphic association foreign key should only be converted to ObjectId when necessary

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.3.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      This is following on from https://github.com/mongoid/mongoid/issues/1084.

      Given models like this, with _id fields of different types:

      class Company
        include Mongoid::Document
        identity :type => String # _id field is a String, not ObjectId
        has_many :posts, as: :postable
      end
      
      class Person
        include Mongoid::Document
        has_many :posts, as: :postable
      end
      
      class Post
        include Mongoid::Document
        belongs_to :postable, polymorphic: true
      end
      

      Queries like this:

      Company.first.postable # Company.first.id => "4e4a3ff20bed3f2feb000036" - a String
      

      will end up doing a find like this:

      foo_test['posts'].find({"postable_id"=>BSON::ObjectId('4e4a3ff20bed3f2feb000036')})
      

      i.e. the id has been converted to ObjectId, and so will not find the required record.

            Assignee:
            Unassigned Unassigned
            Reporter:
            bensymonds Ben Symonds
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: