· 8 years ago · Jul 11, 2018, 02:12 PM
1require 'rubygems'
2require 'dm-core'
3
4DataMapper::Logger.new(STDOUT, :debug)
5DataMapper.setup(:default, 'sqlite3::memory:')
6
7class Foo
8 include DataMapper::Resource
9 property :id, Serial
10 has n, :bars
11end
12
13class Bar
14 include DataMapper::Resource
15 property :id, Serial
16 property :value, Integer
17 belongs_to :foo
18end
19
20DataMapper.auto_migrate!
21
22Foo.create.tap {|foo|
23 foo.bars.create(:value => 1)
24 foo.bars.create(:value => 1)
25}
26Foo.create.tap {|foo|
27 foo.bars.create(:value => 1)
28}
29
30foos = Foo.all
31foos.inspect # ???
32p foos[1].bars.first(:value => 1)
33p foos[1]
34
35foos = Foo.all
36p foos[1].bars.first(:value => 1)
37p foos[1]
38
39
40# mungo:snippets snusnu$ ruby 1021.rb
41# ~ (0.000235) SELECT sqlite_version(*)
42# ~ (0.000155) DROP TABLE IF EXISTS "foos"
43# ~ (0.000022) DROP TABLE IF EXISTS "bars"
44# ~ (0.000036) PRAGMA table_info("foos")
45# ~ (0.000554) CREATE TABLE "foos" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT)
46# ~ (0.000014) PRAGMA table_info("bars")
47# ~ (0.000209) CREATE TABLE "bars" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "value" INTEGER, "foo_id" INTEGER NOT NULL)
48# ~ (0.000214) CREATE INDEX "index_bars_foo" ON "bars" ("foo_id")
49# ~ (0.000052) INSERT INTO "foos" DEFAULT VALUES
50# ~ (0.000088) INSERT INTO "bars" ("value", "foo_id") VALUES (1, 1)
51# ~ (0.000088) INSERT INTO "bars" ("value", "foo_id") VALUES (1, 1)
52# ~ (0.000053) INSERT INTO "foos" DEFAULT VALUES
53# ~ (0.000098) INSERT INTO "bars" ("value", "foo_id") VALUES (1, 2)
54# ~ (0.000052) SELECT "id" FROM "foos" ORDER BY "id"
55# ~ (0.000044) SELECT "id", "value", "foo_id" FROM "bars" WHERE "value" = 1 AND "foo_id" = 2 ORDER BY "id" LIMIT 1
56# #<Bar @id=3 @value=1 @foo_id=2>
57# #<Foo @id=2>
58# ~ (0.000023) SELECT "id" FROM "foos" ORDER BY "id" LIMIT 1 OFFSET 1
59# ~ (0.000036) SELECT "id", "value", "foo_id" FROM "bars" WHERE "value" = 1 AND "foo_id" = 2 ORDER BY "id" LIMIT 1
60# #<Bar @id=3 @value=1 @foo_id=2>
61# ~ (0.000023) SELECT "id" FROM "foos" ORDER BY "id" LIMIT 1 OFFSET 1
62# #<Foo @id=2>