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我可以:
- 删除标记关联
- 删除torrent
删除标签时,我可以:
- 使用该标记从所有种子中删除标记关联
- 删除标签
我怎么能这样做?
尝试使用此插件自动管理关系:
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!
- 无法在Windows上加载此类文件 – do_sqlite3 / 2.0 / do_sqlite3
- Sinatra + Heroku + Datamapper使用dm-sqlite-adapter部署问题
- 使用DataMapper而不是ActiveRecord
- Datamapper成为String
- Windows上是否支持Datamapper的dm_mysql_adapter gem?
- 使用dm-accepts_nested_attributes和dm-is-tree在rails中的2个模型的嵌套表单
- Heroku和Datamapper问题
- 如何使用DataMapper仅获取模型的指定字段?
- 使用Datamapper和Sinatra进行简单搜索