ruby - DataMapper Many-to-Many Delete Constraint -
let's have 2 models 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 create article tag: tag.create(articles: [ article.create ])
if run tag.first.delete
now, returns false since there foreign key constraint due many-to-many relationship. if run tag.first.delete!
deletes tag not association record in article_tags
table.
if use dm-contraints
, set :destroy
destroys article not want.
i can do
tag = tag.first tag.articles = [] tag.save tag.destroy
but seems seems unclean. there better way?
since tag
, article
linked through many-to-many relationship, you'll need first destroy 'articletag' join model references object you're trying delete.
#get tag delete tag = tag.first #deletes rows in article_tags table reference #the tag want delete articletag.all(:tag => tag).destroy #an alternative line above--it same thing tag.article_tags.all.destroy #another alternative--it won't delete articles #the join model references tag tag.articles.all.destroy #finally, obliterate tag tag.destroy
Comments
Post a Comment