我使用Torrent和Tag进行了许多DataMapper / MySQL设置,如下所示:
class Torrent
include DataMapper::Resource
property :id, Serial
property :name, String
property :magnet, Text
property :created_at, DateTime
has n, :tags, :through => Resource
end
class Tag
include DataMapper::Resource
property :id, Serial
property :name, String
property :hits, Integer
has n, :torrents, :through => Resource
end
但是,当尝试通过Torrent.first.destroy
或类似内容销毁torrent时,DataMapper会返回false
。
我尝试了直接的SQL查询,例如delete from torrents where name like '%ubuntu%'
,由于MySQL错误1451而失败:
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`brightswipe`.`tag_torrents`, CONSTRAINT `tag_torrents_torrent_fk` FOREIGN KEY (`torrent_id`) REFERENCES `torrents` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
我认为有一些DataMapper设置,当我删除一个torrent时,我可以:
删除标签时我可以:
我该如何解决这个问题?
答案 0 :(得分:4)
尝试使用此插件自动管理关系:
https://github.com/datamapper/dm-constraints
这将允许您销毁M:M关联,但您必须手动清理关联表:
class Tag
...
has n, :torrents, :through => Resource, :constraint => :skip
class Torrent
...
has n, :tags, :through => Resource, :constraint => :skip
另一个选项是手动删除assocs表中的关系,然后您可以删除没有任何问题的项目,导致您通过从assocs表中删除相应的条目来销毁关系。
基本示例:
tr = Torrent.create
tg = Tag.create
tr.tags << tg
tr.save
tg.torrents << tr
tg.save
# destroying relation
TagTorrent.first(:tag => tg, :torrent => tr).destroy!
# or
tr.tag_torrents(:tag => tg).destroy
# or
tg.tag_torrents(:torrent => tr).destroy
# destroy items
tr.destroy!
tg.destroy!