Datamapper interceptors will not work

I can not understand why the hooks do not 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 the destroy method either from my application or from irb, it returns false . The errors hash is empty, the log message is not printed, and the record is not deleted.

+4
source share
1 answer

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 shows that each of dir_photos is destroyed before dir_item. Instead of using interceptors, you might want to learn dm-constraints . Sort of:

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

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

+5
source

All Articles