All pastes #2097242 Raw Edit

Many-to-Many query

public ruby v1 · immutable
#2097242 ·published 2011-12-29 19:49 UTC
rendered paste body
require 'rubygems'require 'data_mapper' # requires all the gems listed aboveDataMapper::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 => Resourceendclass Word  include DataMapper::Resource  property :id, Serial  property :word, String  has n, :sentences, :through => ResourceendDataMapper.finalizeDataMapper.auto_migrate!s1 = Sentence.new(:text => "Hello world!")whello = Word.new(:word => "Hello")wworld = Word.new(:word => "world")s1.words << whello << wworlds2 = Sentence.new(:text => "Hello Adam!")wadam = Word.new(:word => "Adam")s2.words << whellos2.words << wadams1.saves2.saveputs "\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" }