somebee (owner)

Revisions

gist: 219715 Download_button fork
public
Public Clone URL: git://gist.github.com/219715.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# encoding: utf-8
require 'rubygems'
require 'dm-core'
 
DataMapper::setup(:default, "mysql://root@localhost/dm_core_test")
DataObjects::Mysql.logger = DataObjects::Logger.new(STDOUT, :debug)
 
class Company
  include DataMapper::Resource
 
  property :id, Serial
  property :name, String
  property :owner_id, Integer
  has n, :people
  belongs_to :owner, :model => "Person"
end
 
class Phone
  include DataMapper::Resource
  
  property :id, Serial
  property :nr, Integer
  property :person_id, Integer
  belongs_to :person
end
 
class Person
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :company_id, Integer
  belongs_to :company
  has n, :phones
end
 
DataMapper.auto_migrate!
 
company = Company.create :name => "Kramerica"
company.owner = company.people.new(:name => "Kramer")
company.save
 
c = Company.get(1)
c.owner.phones.new :nr => 10
c.save
 
puts c.owner.inspect # Person has been saved, but the phone has not:
puts c.owner.phones.inspect # => [#<Phone @id=nil @nr=10 @person_id=1 @company_id=nil>] (NOT SAVED)
 
c = Company.get(1)
c.people.first.phones.new :nr => 10
c.save
 
puts c.owner.inspect # Person has been saved:
puts c.owner.phones.inspect # => and this has now been saved to