问题
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