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

(uninitialized constant for polymorphic) Mongoid does not specify the target class when using nested attributes

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

      Hi guys!

      I've been experiencing this issue when using nested attributes and polymorphic associations, the issue is described as follows:

       ruby
      class Product
        include Mongoid::Document
        belongs_to :shop, polymorphic: true
        accepts_nested_attributes_for :shop, autosave: true
      end
      
      class ShopOne
        include Mongoid::Document
      
        field :something, type: String
      
        has_one :product, as: :shop
      end
      
      class ShopTwo
        include Mongoid::Document
      
        field :another_thing, type: Integer
      
        has_one :product, as: :shop
      end
      

      And when I do this

       ruby
      Product.new(shop_type: "ShopOne", shop_attributes: { something: 'Foo' })
      

      It gives me this

      uninitialized constant Shop
      {... path}/mongoid/relations/builders/nested_attributes/one.rb:32
      

      The solution I'm proposing is to override the class_name attribute inside of the metadata class only if the association you're trying to store is polymorphic (See code in the pull request).

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            TheNaoX TheNaoX [X]
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: