Created
January 4, 2010 18:50
-
-
Save sxross/268737 to your computer and use it in GitHub Desktop.
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 "mongo_mapper" | |
MongoMapper.database = 'test' | |
module FindOrCreate | |
def self.included(base) | |
base.class_eval do | |
extend ClassMethods | |
end | |
end | |
module ClassMethods | |
def find_or_create(arg) | |
first(arg) || create(arg) | |
end | |
end | |
end | |
class Photo | |
include MongoMapper::Document | |
key :title, String | |
key :keywords, Array | |
end | |
class Keyword | |
include MongoMapper::Document | |
include FindOrCreate | |
key :keyword, String | |
key :photos, Array | |
end | |
# and then adding: | |
Photo.delete_all | |
Keyword.delete_all | |
i1 = Photo.create(:title => 'one') | |
k = Keyword.find_or_create(:keyword => 'trees') | |
i1.keywords << k.id | |
k.photos << i1.id | |
i1.save; k.save | |
puts Keyword.find(i1.keywords.first).keyword # Find this Photo's first keyword | |
puts Photo.find(Keyword.first.photos.first).title # Find the first Photo that has the first keyword |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment