mongoid多态关联错误

2024-04-08

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

全栈错误 https://gist.github.com/3776248

有什么想法吗?

提前致谢。

Solved

  • 找到动机了

需要将 class_name 添加到关系中

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

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mongoid多态关联错误 的相关文章

随机推荐