2

我有这个带有 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或类似的方式销毁种子时,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 设置,在删除种子时我可以:

  1. 删除标签关联
  2. 删除种子

删除标签时,我可以:

  1. 从具有该标签的所有种子中删除标签关联
  2. 删除标签

我该怎么办?

4

1 回答 1

4

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

https://github.com/datamapper/dm-constraints

这将允许您销毁 M:M assocs,尽管您必须手动清理 assocs 表:

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!
于 2012-10-30T17:11:09.823 回答