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

Polymorphic association query for inverse relation

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

      Work env:
      Rails 4.1.4
      mongoid 4.0.0

      Below is my devise model

      class User
      field :first_name, type: String, default: ""
      field :last_name, type: String, default: ""
      include Mongoid::Document
      belongs_to :user_info, polymorphic: true
      end

      class Employee
      include Mongoid::Document
      belongs_to: :company
      has_one :user, class_name: 'User', as: :user_info, dependent: :destroy
      end

      Below in my query that results into a nil in-spite object being present:

      @employee = @company.employees

      Now if i get first_name of each employee, results into nil
      e.g.

      @user = User.where(user_info: @employees.first)
      @employee = @employees.first.user # this return null

      It fires below query and results in nil:

      MOPED: 127.0.0.1:27017 QUERY database=quikchex_v2_development collection=users selector=

      {"user_info_id"=>BSON::ObjectId('53d88cbf4e696b0bc2020000')}

      flags=[] limit=0 skip=0 batch_size=nil fields=nil runtime: 0.3662ms

      If I fire same query on mongo prompt i get the ouput:

      db.users.find(

      {user_info_id: '53d88cbf4e696b0bc2020000'}

      )

      { "_id" : ObjectId("53d88cbc4e696b0bc2000000"), "first_name" : "Nikunj", "last_name" : "Thakkar", "user_info_id" : "53d88cbf4e696b0bc2020000", "user_info_type" : "Employee" }

      Edit:
      I tried a below native query and it returns me the employee object:
      User.collection.find(

      {user_info_id: '53d88cbf4e696b0bc2020000'}

      )

      The issue then is mongoid converts the user_info_id to BSON::ObjectId('53d88cbf4e696b0bc2020000') while querying, which it shouldn't

      Any help is welcome.
      Thanks

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

              Created:
              Updated:
              Resolved: