DataMapper因关系而无法删除记录

我有许多使用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我可以:

  1. 删除标记关联
  2. 删除torrent

删除标签时,我可以:

  1. 使用该标记从所有种子中删除标记关联
  2. 删除标签

我怎么能这样做?

尝试使用此插件自动管理关系:

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 

另一种选择是手动从关联表中删除关系,然后您可以删除没有任何问题的项目,因为您通过从关联表中删除相应的条目来销毁关系。

基本示例:

 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!