Skip to content

Instantly share code, notes, and snippets.

@solnic
Created November 22, 2010 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solnic/709867 to your computer and use it in GitHub Desktop.
Save solnic/709867 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite::memory")
class User
include DataMapper::Resource
has n, :answers
property :id, Serial
property :name, String
end
class Answer
include DataMapper::Resource
belongs_to :user
has n, :topics, :through => Resource
property :id, Serial
property :text, Text
end
class Topic
include DataMapper::Resource
has n, :answers, :through => Resource
property :name, String, :key => true
end
DataMapper.finalize
DataMapper.auto_migrate!
user = User.create(:name => 'tom')
a = Answer.create(:user => user, :text => 'a1', :topics => [
Topic.first_or_create(:name => 'aboutme'),
Topic.first_or_create(:name => '@onetom')
])
answers = Answer.all(:"user.name" => 'tom', :"topics.name" => 'aboutme')
user_answers = user.answers.all(:"topics.name" => 'aboutme')
puts answers == user_answers # => true
SELECT "answers"."id", "answers"."user_id" FROM "answers" INNER JOIN "users" ON "answers"."user_id" = "users"."id" INNER JOIN "answer_topics" ON "answers"."id" = "answer_topics"."answer_id" INNER JOIN "topics" ON "answer_topics"."topic_name" = "topics"."name" WHERE ("users"."name" = 'tom' AND "topics"."name" = 'aboutme') GROUP BY "answers"."id", "answers"."user_id" ORDER BY "answers"."id"
SELECT "answers"."id", "answers"."user_id" FROM "answers" INNER JOIN "answer_topics" ON "answers"."id" = "answer_topics"."answer_id" INNER JOIN "topics" ON "answer_topics"."topic_name" = "topics"."name" WHERE ("answers"."user_id" = 1 AND "topics"."name" = 'aboutme') GROUP BY "answers"."id", "answers"."user_id" ORDER BY "answers"."id"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment