Created
January 14, 2011 18:34
-
-
Save brianhempel/780006 to your computer and use it in GitHub Desktop.
MongoMapper Polymorphism with Single Collection Inheritance (SCI)
This file contains 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 Commentable | |
include MongoMapper::Document | |
many :comments, :as => :commentable | |
end | |
class Article < Commentable | |
end | |
class Product < Commentable | |
end | |
class Comment | |
include MongoMapper::Document | |
key :text, String | |
belongs_to :commentable, :polymorphic => true | |
end | |
article = Article.create | |
article.comments.create(:text => "Snazzy page!") | |
article.save | |
product = Product.create | |
product.comments.create(:text => "It broke after a month. But it was a good month.") | |
product.comments.create(:text => "Flys like a dream...until it crashes.") | |
product.save | |
article.reload.comments.count # 1 | |
product.reload.comments.count # 2 | |
comment = product.comments.first | |
comment.to_mongo # => | |
{ | |
"_id" => BSON::ObjectId('...'), | |
"text" => "It broke after a month. But it was a good month.", | |
"commentable_type" => "Product", | |
"commentable_id" => BSON::ObjectId('...') | |
} | |
comment.commentable.class # Product | |
comment.commentable.to_mongo # => | |
{ | |
"_id" => BSON::ObjectId('...'), | |
"_type" => "Product" | |
} | |
new_product = Product.new | |
new_comment = Comment.create | |
new_comment.commentable = new_product | |
new_comment.save | |
new_comment.reload.commentable == new_product # true | |
new_product.reload.comments.first == new_comment # true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment