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

Polymorphic association foreign key always converted to ObjectId

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.1.0
    • Affects Version/s: None
    • Component/s: None
    • None

      Say you have a polymorphic setup like the following where all classes involved in the relationship use a custom id field of type String

      class Picture
        include Mongoid::Document
        field :_id, type: String, pre_processed: true, overwrite: true, default: ->{ BSON::ObjectId.new.to_s }
        belongs_to :imageable, polymorphic: true
      end
      
      class Employee
        include Mongoid::Document
        field :_id, type: String, pre_processed: true, overwrite: true, default: ->{ BSON::ObjectId.new.to_s }
        has_many :pictures, as: :imageable
      end
      

      If we create an employee and picture, then link them together so we have:

      Employee.first
      => #<Employee _id: 539f42096c75633c62010000 >
      Picture.first
      => #<Picture _id: 539f428b6c75633c62020000, imageable_type: "Employee", imageable_id: "539f42096c75633c62010000">
      Picture.first.imageable_id == Employee.first.id
      => true
      Picture.first.imageable_id.class
      => String
      

      Then try to access the employee's pictures via the association, nothing is found - even though there is a picture associated with the employee

      Employee.first.pictures
      => []   # this should've returned the first picture
      

      Underneath the covers, the selector tries to find an imageable_id of type BSON::ObjectId, not String.

       MOPED: 127.0.0.1:27017 QUERY        database=dev collection=pictures selector={"imageable_id"=>BSON::ObjectId('539f42096c75633c62010000'), "imageable_type"=>"Employee"} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            allankeller allankeller
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: