-
Type: Task
-
Resolution: Done
-
Priority: Major - P3
-
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:
- Insert data
item = Item.create(name: "Item1")
- 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
- Save labels to item
item.upc_label = upc
item.nutritional_label = nutritional
item.warning_label = warning
item.save!
- 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