以前の質問。
https://teratail.com/questions/157540
https://teratail.com/questions/162431
現状以下のようなテーブルがあります。
article id: integer title: string deleted_article id: integer article_id: integer title: string
articleを削除後、deleted_articleに情報を退避する感じです。
ここで上記一つ目の質問に書いてあるid再利用がarticleテーブルで起きてしまうため以下のような状況になってしまいます。
articleテーブル
id | title |
---|---|
3 | title3 |
4 | title4 |
5 | title5 |
1 | title6 |
deleted_articleテーブル
id | article_id | title |
---|---|---|
1 | 1 | title1 |
2 | 2 | title2 |
ここでdeleted_articleのarticle_idはuniqueなので、title: "title6"
の記事が削除できなくなっています。
ここでアプリケーション(Rails)側でdeleted_articlesのarticle_idに存在しないidのみをarticlesに挿入したいのですが、以下のような実装はどう思いますか?
(rollbackが起きるとauto incrementがプラスされるようなのでそれを利用しています。)
ruby
1loop do 2 begin 3 Article.transaction do 4 article = Article.create!(title: ’test’) 5 raise ActiveRecord::Rollback if DeletedArticle.exists?(article_id: article.id) 6 break 7 end 8 rescue 9 next 10 end 11end
また、もし他に良い案があれば教えてください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/13 03:07