我在使用具有多态字段的mongoid-3.0.6时遇到了一些问题。 使用rails 3.2.8和ruby 1.9.3
使用正常的多态关系:
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
通过元数据可以获得相同的关联:
>> 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>
但是当我跑步时
>> item.product = Shirt.new or >> item.build_product
我总是犯同样的错误
NameError: uninitialized constant Product
有什么想法?
提前致谢。
解决
需要将class_name添加到关系
has_one :product, as: :itemizable, class_name: "Toy"