require 'rubygems' require 'data_mapper' # requires all the gems listed above DataMapper::Logger.new($stdout, :debug) # An in-memory Sqlite3 connection: DataMapper.setup(:default, 'sqlite::memory:') # A Sqlite3 connection to a persistent database # DataMapper.setup(:default, 'sqlite:///tmp/x') class Sentence include DataMapper::Resource property :id, Serial property :text, String has n, :words, :through => Resource end class Word include DataMapper::Resource property :id, Serial property :word, String has n, :sentences, :through => Resource end DataMapper.finalize DataMapper.auto_migrate! s1 = Sentence.new(:text => "Hello world!") whello = Word.new(:word => "Hello") wworld = Word.new(:word => "world") s1.words << whello << wworld s2 = Sentence.new(:text => "Hello Adam!") wadam = Word.new(:word => "Adam") s2.words << whello s2.words << wadam s1.save s2.save puts "\n\nQuerying via Sentence.all(:words => { :word => 'Hello' }) :\n" Sentence.all(:words => { :word => "Hello" }).each { |s| puts "This has 'Hello': #{s.text}\n" } puts "\n\nVia adapter.select, with sentences.id in inner query:\n" result = DataMapper.repository(:default).adapter.select('SELECT "id", "text" FROM "sentences" WHERE "id" IN (SELECT "sentences"."id" FROM "words" INNER JOIN "sentence_words" ON "words"."id" = "sentence_words"."word_id" INNER JOIN "sentences" ON "sentence_words"."sentence_id" = "sentences"."id" WHERE "words"."word" = "Hello") ORDER BY "id"') result.each { |s| puts "This has 'Hello': #{s.text}\n" }