Created
July 19, 2009 08:25
-
-
Save fcoury/149845 to your computer and use it in GitHub Desktop.
Example of polymorphic one to many association using mongomapper
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
require 'mongomapper' | |
class Media | |
include MongoMapper::EmbeddedDocument | |
key :file, String | |
end | |
class Video < Media | |
key :length, Integer | |
end | |
class Image < Media | |
key :width, Integer | |
key :height, Integer | |
end | |
class Music < Media | |
key :bitrate, String | |
end | |
class Catalog | |
include MongoMapper::Document | |
many :medias, :polymorphic => true | |
end | |
catalog = Catalog.new | |
catalog.medias = [ | |
Video.new("file" => "video.mpg", "length" => 3600), | |
Music.new("file" => "music.mp3", "bitrate" => "128kbps"), | |
Image.new("file" => "image.png", "width" => 800, "height" => 600) | |
] | |
catalog.save #=> true | |
from_db = Catalog.find(catalog.id) | |
from_db.medias.size #=> 3 | |
from_db.medias[0].file #=> "video.mpg" | |
from_db.medias[0].length #=> 3600 | |
from_db.medias[1].file #=> "music.mp3" | |
from_db.medias[1].bitrate #=> "128kbps" | |
from_db.medias[2].file #=> "image.png" | |
from_db.medias[2].width #=> 800 | |
from_db.medias[2].height #=> 600 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment