我在使用带有多态字段的 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"