Asociaciones Simples

The types of associations currently in DataMapper are:

has n  
has 1 
belongs_to 
has n, :things, :through => Resource   
has n, :things, :through => :model

Este código se encuentra en: app.rb

[~/rubytesting/database/datamapper/two(master)]$ cat app.rb 
require 'data_mapper'

DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/example.db")

class Post
  include DataMapper::Resource

  property :id, Serial
  property :text, Text

  has n, :comments
end

class Comment
  include DataMapper::Resource

  property :id,     Serial
  property :text, Text

  belongs_to :post  # defaults to :required => true

end

DataMapper.finalize

require  'dm-migrations'

#DataMapper.auto_migrate!
DataMapper.auto_upgrade!
The belongs_to method accepts a few options.

Arrancamos Pry

[~/rubytesting/database/datamapper/two]$ pry
y cargamos ./app.rb
[1] pry(main)> load './app.rb'
 ~ (0.000397) PRAGMA table_info("posts")
 ~ (0.000019) SELECT sqlite_version(*)
 ~ (0.001237) CREATE TABLE "posts" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "text" TEXT)
 ~ (0.000011) PRAGMA table_info("comments")
 ~ (0.000986) CREATE TABLE "comments" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "text" TEXT, "post_id" INTEGER NOT NULL)
 ~ (0.000964) CREATE INDEX "index_comments_post" ON "comments" ("post_id")
=> true
Este es el esquema de la base de datos creada a partir de las clases Post y Comment:
[~/rubytesting/database/datamapper/two(master)]$ sqlite3 example.db 
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
CREATE TABLE "comments" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
                         "text" TEXT, 
                         "post_id" INTEGER NOT NULL);
CREATE TABLE "posts" ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
                      "text" TEXT);
CREATE INDEX "index_comments_post" ON "comments" ("post_id");

Ahora podemos crear un objeto Post:

[2] pry(main)> pp = Post.create(:text => 'hello world!')
 ~ (0.000888) INSERT INTO "posts" ("text") VALUES ('hello world!')
=> #<Post @id=1 @text="hello world!">
Sus comments están vacíos:
[3] pry(main)> pp.comments
 ~ (0.000051) SELECT "id", "post_id" FROM "comments" WHERE "post_id" = 1 ORDER BY "id"
=> []

Adding resources to a relationship, can be done in different ways.

Casiano Rodriguez León 2015-01-07