-
Type: Bug
-
Resolution: Duplicate
-
Priority: Major - P3
-
Affects Version/s: None
-
Component/s: None
-
None
class Parent include Mongoid::Document embeds_one :embedded end class Embedded include Mongoid::Document embedded_in :parent has_many :items, as: :itemable end class Item include Mongoid::Document belongs_to :itemable, polymorphic: true end
Items are only created like this
parent.embedded.items.create(...)
and that ensures that itemable_type and itemable_id are set properly.
Now, when I use Item like this
item = Item.find('42')
item.itemable
#=> nil
its itemable association always returns nil. That is completely reasonable behavior given that the itemable in question is embedded and could not be loaded through just its type and id.
However, when loading an item like this:
parent.embedded.items.find('42')
the case is slightly, but relevantly different. Here, the itemable is known beforehand and could be set from within #find.
For the time being, I have implemented the behavior in an association extension like this
class Embedded include Mongoid::Document embedded_in :parent has_many :items, as: :itemable do def find(*args) super.tap { |ref| ref.itemable = base } end end end
but I'm hoping that Mongoid could handle this.
- is related to
-
MONGOID-2882 Set base relation on has_many enumerable objects
- Closed