· 8 years ago · Jul 14, 2018, 07:30 AM
1require 'rubygems'
2require 'dm-core'
3
4DataMapper::Logger.new(STDOUT, :debug)
5DataMapper.setup(:default, 'sqlite3::memory:')
6
7class Post
8 include DataMapper::Resource
9
10 property :id, Serial
11 property :comments_count, Integer, :default => 0
12 has n, :comments
13end
14
15class Comment
16 include DataMapper::Resource
17
18 property :id, Serial
19 belongs_to :post
20
21end
22
23class User
24 include DataMapper::Resource
25
26 property :id, Serial
27 property :groups_count, Integer
28
29 has n, :group_memberships
30 has n, :groups, :through => :group_memberships, :via => :group
31end
32
33class Group
34 include DataMapper::Resource
35
36 property :id, Serial
37 property :members_count, Integer
38
39 has n, :group_memberships
40 has n, :members, "User", :through => :group_memberships, :via => :member
41end
42
43class GroupMembership
44 include DataMapper::Resource
45
46 property :id, Serial
47
48 belongs_to :group
49 belongs_to :member, "User", :child_key => [:user_id]
50end
51
52
53DataMapper.auto_migrate!
54
55__END__
56
57mungo:snippets snusnu$ ruby jacques.rb
58 ~ (0.000151) SELECT sqlite_version(*)
59 ~ (0.000096) DROP TABLE IF EXISTS "posts"
60 ~ (0.000015) DROP TABLE IF EXISTS "comments"
61 ~ (0.000018) DROP TABLE IF EXISTS "users"
62 ~ (0.000016) DROP TABLE IF EXISTS "groups"
63 ~ (0.000015) DROP TABLE IF EXISTS "group_memberships"
64 ~ (0.000042) PRAGMA table_info("posts")
65 ~ (0.000414) CREATE TABLE "posts" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "comments_count" INTEGER DEFAULT 0)
66 ~ (0.000009) PRAGMA table_info("comments")
67 ~ (0.000117) CREATE TABLE "comments" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "post_id" INTEGER NOT NULL)
68 ~ (0.000126) CREATE INDEX "index_comments_post" ON "comments" ("post_id")
69 ~ (0.000009) PRAGMA table_info("users")
70 ~ (0.000110) CREATE TABLE "users" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "groups_count" INTEGER)
71 ~ (0.000008) PRAGMA table_info("groups")
72 ~ (0.000105) CREATE TABLE "groups" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "members_count" INTEGER)
73 ~ (0.000017) PRAGMA table_info("group_memberships")
74 ~ (0.000113) CREATE TABLE "group_memberships" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "group_id" INTEGER NOT NULL)
75 ~ (0.000169) CREATE INDEX "index_group_memberships_member" ON "group_memberships" ("user_id")
76 ~ (0.000204) CREATE INDEX "index_group_memberships_group" ON "group_memberships" ("group_id")