Photos & Tags Revision 363533633036 (Fri Oct 14 2011 at 15:00) - Diff Link to this snippet: https://friendpaste.com/744xr8OvLiBlG5lEhXYrfQ Embed: manni perldoc borland colorful default murphy trac fruity autumn bw emacs pastie friendly Show line numbers Wrap lines 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889require 'rubygems'require 'relaxdb'# Specify the db to be used. Create it in CouchDB yourself locally.RelaxDB::Database.set_std_db :host => "localhost", :port => 5984, :db => "photos"## Define the classes#class Photo < RelaxDB::Document property :name property :tagsendclass Tag < RelaxDB::Document property :name property :photos end## Create the views#tags_view = <<MAP_FUNC function(doc) { if(doc.class == "Tag" && doc.photos) { var i; for(i = 0; i < doc.photos.length; i++) { emit(doc.photos[i], doc); } } }MAP_FUNCphotos_view = <<MAP_FUNC function(doc) { if(doc.class == "Photo" && doc.tags) { var i; for(i = 0; i < doc.tags.length; i++) { emit(doc.tags[i], doc); } } }MAP_FUNCDesignDocument.get(Photo).add_view_to_data("all_tags", tags_view).saveDesignDocument.get(Tag).add_view_to_data("all_photos", photos_view).save## Insert some data#Photo.destroy_all!Tag.destroy_all!mg = Photo.new(:_id => "mg", :name => "Migration").savedes = Photo.new(:_id => "des", :name => "Dar es Salaam").savewd = Tag.new(:_id => "wd", :name => "wildebeest").savetz = Tag.new(:_id => "tz", :name => "tanzania").save# Being forced to use ids and set the relationship on both sides is clunky and error # prone, but it's no more than a current limitation of the librarymg.tags = [wd._id, tz._id]des.tags = [tz._id]wd.photos = [mg._id]tz.photos = [mg._id, des._id]RelaxDB.bulk_save(mg, des, wd, tz)## Examine the data, confirm in the CouchDB log that n+1 requests aren't being made#mg = Photo.all_by(:name) { |q| q.key = "Migration"}[0]mg_tags = Photo.view("all_tags?key=\"#{mg._id}\"")puts mg_tags.inject("Tags for #{mg.name}") { |m, t| m << " '#{t.name}'" }tz = Tag.all_by(:name) { |q| q.key = "tanzania" }[0]tz_photos = Tag.view("all_photos?key=\"#{tz._id}\"")puts tz_photos.inject("Photos for #{tz.name}") { |m, p| m << " '#{p.name}'" }