#846 ✓resolved
Sindre Aarsaether

Deleting self-referential 1:m collection destroys _every_ resource of model

Reported by Sindre Aarsaether | May 8th, 2009 @ 03:04 AM

This was a little hard to reproduce, but it happens consistently in the example below:



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 # => []

Gist of it: http://gist.github.com/108699

PS! This is on the dkubb/sel-branch. But since it is to be merged back into next, I still report it. It probably happens on dm-core/next to (i would presume).

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

People watching this ticket

Referenced by

Pages