由于关系,DataMapper无法删除记录 [英] DataMapper can't delete record because of relation

查看:103
本文介绍了由于关系,DataMapper无法删除记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Torrent和Tag进行了很多这种DataMapper/MySQL设置,如下所示:

I have this many-many DataMapper/MySQL setup with Torrent and Tag, as follows:

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.

When trying to destroy a torrent, however, via Torrent.first.destroy or something similar, DataMapper returns false.

我尝试了像delete from torrents where name like '%ubuntu%'这样的直接SQL查询,由于MySQL错误1451,该查询失败了:

I tried straight SQL queries like delete from torrents where name like '%ubuntu%', which failed because of MySQL error 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设置,通过该设置,可以在删除洪流时进行以下操作:

I figure there's some DataMapper setup whereby when deleting a torrent I can:

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

当删除标签时,我可以:

And when deleting a tag I can:

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

我该怎么办?

推荐答案

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

try using this plugin to have relations managed automatically:

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

这将使您能够销毁M:M assoc,尽管您必须手动清理assocs表:

This will allow you to destroy M:M assocs though you'll have to cleanup the assocs table manually:

class Tag
  ...
  has n, :torrents, :through => Resource, :constraint => :skip

class Torrent
  ...
  has n, :tags, :through => Resource, :constraint => :skip

另一种选择是手动从assocs表中删除该关系,然后可以删除项目而不会出现任何问题,并通过从assocs表中删除相应的条目来破坏该关系.

Another option is to remove the relation from assocs table manually, then you'll can remove items without any issues, cause you destroyed the relation by removing corresponding entry from assocs table.

基本示例:

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!

这篇关于由于关系,DataMapper无法删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆