DataMapper多对多删除约束

时间:2013-05-04 15:43:15

标签: ruby datamapper ruby-datamapper

假设我们有两个具有多对多关系的模型:

class Tag
  include DataMapper::Resource
  property :id, Serial
  has n, :articles, through: Resource
end

class Article
  include DataMapper::Resource
  property :id, Serial
  has n, :tags, through: Resource
end

现在,如果我创建一个带有标记的文章:Tag.create(articles: [ Article.create ])

如果我现在运行Tag.first.delete,它会返回false,因为由于多对多关系存在外键约束。如果我运行Tag.first.delete!,它将删除标签,但不删除article_tags表中的关联记录。

如果我使用dm-contraints并将所有内容设置为:destroy,那么它也会破坏不属于我想要的文章。

我能做到

tag = Tag.first
tag.articles = []
tag.save
tag.destroy

但这看起来似乎不洁净。还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

由于TagArticle是通过多对多关系链接的,因此您需要首先销毁任何引用您要删除的对象的“ArticleTag”连接模型。

#get the tag to delete
tag = Tag.first

#deletes all rows in the article_tags table that reference
#the tag you want to delete
ArticleTag.all(:tag => tag).destroy

#an alternative to the line above--it does the same thing
tag.article_tags.all.destroy

#another alternative--it won't delete the articles only
#the join model that references the tag
tag.articles.all.destroy

#finally, obliterate the tag
tag.destroy