【问题标题】:DataMapper Many-to-Many Delete ConstraintDataMapper 多对多删除约束
【发布时间】:2013-04-28 20:51:59
【问题描述】:

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

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

但这似乎不干净。有没有更好的办法?

【问题讨论】:

  • xato,你找到更好的方法了吗?

标签: ruby datamapper ruby-datamapper


【解决方案1】:

由于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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    相关资源
    最近更新 更多