Skip to content

Instantly share code, notes, and snippets.

@brianhempel
Created January 14, 2011 18:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianhempel/780006 to your computer and use it in GitHub Desktop.
Save brianhempel/780006 to your computer and use it in GitHub Desktop.
MongoMapper Polymorphism with Single Collection Inheritance (SCI)
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