2010-09-16 87 views
4

无法理解为什么挂钩不起作用。我有以下型号:Datamapper的挂钩不起作用

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 

当我打电话destroy方法无论是从我的应用程序或IRB,它返回falseerrors散列为空,日志消息不打印,记录不会被删除。

+0

问题通过'destroy'覆盖解决,但我很有趣为什么钩子不起作用。 – 2010-09-16 08:32:44

回答

5

这个钩子对我的作品(红宝石1.9.2/1.0.2 DM):

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将被销毁,而这也将通过数据库级​​别的外键约束强制执行。

+0

谢谢!我不知道:约束:) – vitorbal 2012-05-05 02:24:31