· 8 years ago · Mar 08, 2018, 11:14 PM
1require 'rubygems'
2
3gem 'dm-core', '0.10.0'
4require 'dm-core'
5
6class Post
7 include DataMapper::Resource
8
9 def self.default_repository_name
10 :post
11 end
12
13 property :id, Serial
14 property :title, String
15
16 has n, :comments, :repository => :comment
17end
18
19class Comment
20 include DataMapper::Resource
21
22 def self.default_repository_name
23 :comment
24 end
25
26 property :id, Serial
27 property :body, Text
28 property :post_id, String # for argument sake
29
30 belongs_to :post, :repository => :post
31end
32
33DataMapper.setup(:comment, "sqlite3::memory:")
34DataMapper.setup(:post, :adapter => :in_memory)
35DataObjects::Sqlite3.logger = DataObjects::Logger.new(STDOUT, 0)
36DataMapper.auto_migrate!
37
38Post.create(:title => 'Post 1')
39Post.create(:title => 'Post 2')
40 # !> method redefined; discarding old to_datetime
41Comment.create(:body => 'first!', :post_id => '1')
42Comment.create(:body => 'first!', :post_id => '2')
43
44Comment.all.map { |comment| comment.post } # => [nil, nil]
45# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.000511) SELECT sqlite_version(*)
46# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.000399) DROP TABLE IF EXISTS "comments"
47# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.000042) PRAGMA table_info("comments")
48# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.001048) CREATE TABLE "comments" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "body" TEXT, "post_id" VARCHAR(50))
49# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.000115) INSERT INTO "comments" ("body", "post_id") VALUES ('first!', '1')
50# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.000057) INSERT INTO "comments" ("body", "post_id") VALUES ('first!', '2')
51# >> Thu, 25 Jun 2009 17:53:16 GMT ~ debug ~ (0.000081) SELECT "id", "post_id" FROM "comments" ORDER BY "id"