我需要有一个模型,这将像一个嵌入式和非嵌入式的行为。
例如,如果我想将此模型存储为嵌入式:
class MenuPosition
include Mongoid::Document
field :name, type: String
field :category, type: String我需要添加
embedded_in :menu干杯。
另一方面,如果我在模型中添加这一行,我不能将此模型存储为非嵌入式:
position = {
"name" => "pork",
"category" => "meal",
"portion" => 100
}
MenuPosition.create(position)错误消息:
NoMethodError:
undefined method `new?' for nil:NilClass我可以将一个模型用于嵌入式和非嵌入式文档吗?
发布于 2012-05-18 06:32:25
在我们的项目中,我们也有类似的事情。我们所做的是将字段定义为一个模块。有点像这样:
module SpecialFields
extend ActiveSupport::Concern
included do
field :my_field, type: String
field :my_other_field, type: String
end
end然后在要嵌入的类中,只需执行以下操作:
include SpecialFields在您希望单独存储为非嵌入式文档的类中,执行以下操作:
class NotEmbeddedDoc
include Mongoid::Document
include SpecialFields
end在我们的项目中,这在一些事情上工作得很好。但是,它可能不适合您的情况,因为您想要嵌入许多。我认为这只适用于嵌入一个案例。我把它贴在这里,以防它对人们有帮助。
https://stackoverflow.com/questions/10140953
复制相似问题