Skip to content

Instantly share code, notes, and snippets.

@michalvalasek
Last active May 31, 2016 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalvalasek/244923867297fea7eb76bb4dfdfbd36c to your computer and use it in GitHub Desktop.
Save michalvalasek/244923867297fea7eb76bb4dfdfbd36c to your computer and use it in GitHub Desktop.
Mongoid - embed multiple documents of different types
class Article
include Mongoid::Document
field :title, type: String
embeds_many :widgets, as: :widgetable
end
class Widget
include Mongoid::Document
embedded_in :widgetable, polymorphic: true
end
class Widget::Banner < Widget
field :title, type: String
end
class Widget::Place < Widget
field :name, type: String
end
a = Article.new({title: "Example Article"})
a.widgets.build({title: "Banner One"}, Widget::Banner)
a.widgets.build({name: "New York"}, Widget::Place)
a
# => #<Article _id: 574d89bb618eade4080aa284, title: "Testovaci">
a.widgets
# => [#<Widget::Banner _id: 574d8a2c618eade4080aa286, title: "Example Article">, #<Widget::Banner _id: 574d8a26618eade4080aa285, _type: "Widget::Banner", title: "Banner One">, #<Widget::Place _id: 574d8a4d618eade4080aa287, _type: "Widget::Place", name: "New York">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment