mongoid polymorphic association error

我怕爱的太早我们不能终老 提交于 2019-12-10 20:37:25

问题


I'm having some problems using mongoid-3.0.6 with polymorphic fields. Using rails 3.2.8 and ruby 1.9.3

Using a normal polymorphic relation:

class Shirt
  include Mongoid::Document

  field          :name,        localize: true

  belongs_to     :itemizable,  polymorphic: true
end

class Item
  include Mongoid::Document

  field       :price,     type: Float
  field       :quantity,  type: Integer,   :default => 1

  has_one     :product,   as: :itemizable

  accepts_nested_attributes_for :product
end

The same association is available through the metadata:

>> Item.reflect_on_association(:product)
#<Mongoid::Relations::Metadata
   autobuild:    false,
   class_name:   Product,
   cyclic:       nil,
   dependent:    nil,
   inverse_of:   nil,
   key:          _id,
   macro:        has_one,
   name:         product,
   order:        nil,
   polymorphic:  true,
   relation:     Mongoid::Relations::Referenced::One,
   setter:       product=,
   versioned:    false>

>> item = Item.new
#<Item _id: 50606c1668ce87692e000003, _type: nil, created_at: nil, updated_at: nil, deleted_at: nil, price: nil, quantity: 1>

but when i run

>> item.product = Shirt.new or >> item.build_product

i got always the same error

NameError: uninitialized constant Product

Full stack error

Any thoughts?

Thanks in advance.

Solved

  • Found the motive

Need to add the class_name to the relation

has_one     :product,   as: :itemizable, class_name: "Toy"

来源:https://stackoverflow.com/questions/12567481/mongoid-polymorphic-association-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!