无法理解为什么钩子不起作用。我有以下型号:
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
当我从我的app或irb调用destroy
方法时,它会返回false
。 errors
哈希为空,日志消息不打印,记录也不会删除。
答案 0 :(得分:5)
这个钩子适用于我(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
DM记录器显示每个dir_photos在dir_item之前被销毁。您可能希望考虑使用dm-constraints
而不是使用挂钩。有类似的东西:
has n, :dir_photos, :constraint => :destroy
你可以确定dir_item被销毁时将销毁所有dir_photos,这也将由数据库级外键约束强制执行。