2013-05-04 26 views
3

比方說,我們有兩個型號,一個多一對多的關係:如果我Tag.create(articles: [ Article.create ])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.first.delete,由於存在由多對多關係造成的外鍵約束,因此它返回false。如果我運行Tag.first.delete!,它會刪除標記,但不會刪除article_tags表中的關聯記錄。

如果我使用dm-contraints並將所有設置設置爲:destroy它也銷燬不是我想要的文章。

我可以做

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

但這似乎看起來不乾淨。有沒有更好的辦法?

+0

xato,你有沒有找到更好的方法? – fernandospr 2014-03-26 17:44:37

回答

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