Last active
May 31, 2016 13:15
-
-
Save michalvalasek/244923867297fea7eb76bb4dfdfbd36c to your computer and use it in GitHub Desktop.
Mongoid - embed multiple documents of different types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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