gpt4 book ai didi

ruby - Datamapper 的钩子(Hook)不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 07:31:12 25 4
gpt4 key购买 nike

无法理解为什么 Hook 不起作用。我有以下模型:

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

当我从我的应用程序或 irb 调用 destroy 方法时,它返回 falseerrors 哈希为空,日志消息不打印且记录不删除。

最佳答案

这个钩子(Hook)对我有用(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 之前被销毁。不过,您可能不希望使用钩子(Hook),而是考虑使用 dm-constraints。像这样:

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

可以肯定的是,当 dir_item 被销毁时,所有的 dir_photos 都将被销毁,这也将由数据库级外键约束强制执行。

关于ruby - Datamapper 的钩子(Hook)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3724580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com