问题描述:

I need to have a model which will behave like a embedded and not-embedded.

For example if I want to store this model as embedded:

class MenuPosition

include Mongoid::Document

field :name, type: String

field :category, type: String

I need to add

 embedded_in :menu

to it.

On the other side, if I add this line in the model I cannot store this model as not-embedded:

position = {

"name" => "pork",

"category" => "meal",

"portion" => 100

}

MenuPosition.create(position)

error message:

NoMethodError:

undefined method `new?' for nil:NilClass

Can I use one model for embedded and not-embedded documents?

网友答案:

In our project we had a similar thing. What we did is define the fields as a module. A bit like this:

module SpecialFields
  extend ActiveSupport::Concern

  included do
    field :my_field, type: String
    field :my_other_field, type: String
  end
end

Then in your class where you want to embed, just do:

include SpecialFields

In your class that you'd like to store separately as a non-embedded document, do this:

class NotEmbeddedDoc
  include Mongoid::Document

  include SpecialFields
end

This worked pretty well in our project for a few things. However, it might not be appropriate in your case since you want to embed many. This only really works for embeds one cases I think. I have posted it here in case it helps people.

相关阅读:
Top