4

Can't understand why hooks don't work. I have the following model:

class DirItem
  include DataMapper::Resource

  # property <name>, <type>
  property :id, Serial
  property :dir_cat_id, Integer, :required => true
  property :title, String, :required => true
  property :price, Integer, :default => 0

  belongs_to :dir_cat
  has n, :dir_photos
  has n, :dir_field_values

  before :destroy do
    logger.debug "==============DESTROYING ITEM ##{id}, TITLE
#{title}"
    dir_field_values.destroy
    dir_photos.destroy
  end
end

When I call destroy method either from my app or irb, it returns false. The errors hash is empty, the log message doesn't print and the record won't delete.

1 Answers1

5

This hook works for me (ruby 1.9.2 / DM 1.0.2):

require 'rubygems'
require 'dm-core'
require 'dm-migrations'


# setup the logger
DataMapper::Logger.new($stdout, :debug)

# connect to the DB
DataMapper.setup(:default, 'sqlite3::memory:')

class DirItem
  include DataMapper::Resource

  # property <name>, <type>
  property :id, Serial
  property :dir_cat_id, Integer, :required => true
  property :title, String, :required => true
  property :price, Integer, :default => 0

  has n, :dir_photos

  before :destroy do
    dir_photos.destroy
  end
end

class DirPhoto
  include DataMapper::Resource
  property :id, Serial
  belongs_to :dir_item
end

DataMapper.finalize.auto_migrate!

@i = DirItem.create(:title => 'Title', :dir_cat_id => 1)
@i.dir_photos.create
@i.dir_photos.create
@i.dir_photos.create
@i.destroy

The DM logger reveals that each of the dir_photos are destroyed before the dir_item is. Instead of using hooks, you might want to look into using dm-constraints though. With something like:

has n, :dir_photos, :constraint => :destroy

you can be sure that all the dir_photos will be destroyed when the dir_item is destroyed, and this will also be enforced by database level foreign key constraints.

namelessjon
  • 907
  • 5
  • 8