Created
May 8, 2009 07:29
-
-
Save somebee/108699 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'dm-core' | |
DataMapper.setup(:default, | |
:adapter => 'mysql', | |
:host => 'localhost', | |
:username => 'root', | |
:database => 'dm_core_test', | |
:encoding => 'utf8' | |
) | |
DataObjects::Mysql.logger = DataObjects::Logger.new(STDOUT, :debug) | |
class Rate | |
include DataMapper::Resource | |
property :id, Serial | |
property :name, String | |
property :rate, BigDecimal | |
has n, :postings | |
end | |
class Posting | |
include DataMapper::Resource | |
property :id, Serial | |
property :date, Date | |
property :amount, BigDecimal, :scale => 2, :precision => 10 | |
belongs_to :rate | |
has n, :children, :model => Posting, :child_key => [:parent_id] | |
before :save do | |
if attribute_dirty?(:rate_id) | |
children.destroy if saved? | |
children.new :date => date, :amount => 20 | |
end | |
end | |
end | |
Rate.auto_migrate! | |
Posting.auto_migrate! | |
r = Rate.create(:name => "25% Incoming VAT", :rate => 25) # id 1 | |
p1 = Posting.create(:amount => 100.00, :rate_id => 1) # id 1 | |
p2 = Posting.create(:amount => 100.00, :rate_id => 1) # id 3 (a child is created) | |
# There are now 4 postings saved in the database. | |
# Then we update p2, changing rate_id. As you can see | |
# In the before-block, it will try to delete its children | |
# This deletes ALL postings, including itself. | |
p2.update(:rate_id => nil) | |
# Tada, all the postings (including p2 itself) are gone: | |
puts Posting.all.inspect # => [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment