3

Let's say we have two models with a many-to-many relation:

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

Now if I create an article with a tag: Tag.create(articles: [ Article.create ])

If I run Tag.first.delete now, it returns false since there is a foreign key constraint due to the many-to-many relationship. If I run Tag.first.delete! it deletes the Tag but not the association record in the article_tags table.

If I use dm-contraints and set everything to :destroy it also destroys the Article which is not what I want.

I can do

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

but this seems seems unclean. Is there a better way?

1 Answers1

2

Since Tag and Article are linked through a many-to-many relationship, you'll need to first destroy any 'ArticleTag' join model that references the object you're trying to delete.

#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
gowansg
  • 785
  • 1
  • 8
  • 15