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

Model with multiple has_one results in same id

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

      Hello, I am having a problem where has_one would return the same id each time. Here is a rough example (simplified from my more complex application):

      class Label
      include Mongoid::Document
      belongs_to :item
      field :data
      end

      class Item
      include Mongoid::Document
      has_one :upc_label, :class_name => 'Label', :inverse_of => :item
      has_one :nutritional_label, :class_name => 'Label', :inverse_of => :item
      has_one :warning_label, :class_name => 'Label', :inverse_of => :item
      field :name
      end

      I run the following:

      1. Insert data
        item = Item.create(name: "Item1")
      1. Insert labels
        upc = Label.create(data: "upc")
        nutritional = Label.create(data: "nutritional")
        warning = Label.create(data: "warning")

      puts upc._id
      > 53de0588737175687c060000

      puts nutritional._id
      > 53de0588737175687c070000

      puts warning._id
      > 53de0588737175687c080000

      1. Save labels to item
        item.upc_label = upc
        item.nutritional_label = nutritional
        item.warning_label = warning
        item.save!
      1. Now retrieve the item and print out label ids
        retrieved_item = Item.find(item._id)

      puts retrieved_item.upc_label._id
      > 53de0588737175687c080000

      puts retrieved_item.nutritional_label._id
      > 53de0588737175687c080000

      puts retrieved_item.warning_label._id
      > 53de0588737175687c080000

      As you can see, even though the labels have different IDs, the item still returns the same label ID for each has_one. It looks like the last label (warning_label) overwrites all the other ones in the Item model.

      I expected Item to have the different label ids, but that was not the case.

      I am using:

      • ruby 2.1.2p95
      • mongoid (4.0.0)
      • mongo 2.4.10

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

              Created:
              Updated:
              Resolved: