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

Objects loaded through an association should have their inverse association set

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • 7.0.0
    • 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.

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            mschuerig mschuerig
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: