0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails5 has_many dependent: :delete_allでミスるとレコード全件消える

0
Posted at

なんかたまにテーブルのレコード全部消えると思って調べた。

たまに1テーブルのレコードが全件消える。いつも同じテーブルというわけではない。
もちろん、全レコード削除するようなコード書いてないのに消える。
怖いので調べた。

ログ見てたら怪しいやついた。

jiburi-web | Started GET "/kamikakushi" for 172.22.0.1 at 2020-03-06 17:09:18 +0900
jiburi-web | Cannot render console from 172.22.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
jiburi-web |   Chihiro Destroy (6.1ms)  DELETE FROM `chihiros`
jiburi-web |   ↳ app/models/chihiro.rb:3:in `<class:Luser>'
jiburi-web |   
jiburi-web | ArgumentError (The :dependent option must be one of [:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception], but is :3):

DELETE FROM chihirosしているやつがいた。
直後のエラーが怪しいので更に調査。

調べたら再現できた

chihiro.rb
class Chihiro < ApplicationRecord
  has_many :sens, dependent: :delete_all

  # :delete_allをミスして「:」を忘れ、delete_allにしてた。
  has_many :aburayas, dependent: delete_all

色々試した結果、わかったことは2つ。

  1. chihirosテーブルにレコードが存在する状態で、上のようなソースになっていると、DELETE FROM chihirosが実行される。
  2. 外部キーがきちんと貼られていれば、以下のようなActiveRecord::InvalidForeignKey が発生するのでレコードは消えない。
jiburi-web | ActiveRecord::InvalidForeignKey (Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails (`jiburi`.`chihiros`, CONSTRAINT `fk_rails_7f965bd3db` FOREIGN KEY (`aburaya_id`) REFERENCES `aburayas` (`id`))):

なぜそうなるのかわからない

理由がわからなくて辛い。。
どこのソースを追えばいいのか。
が、ミスしっぱなしで放置しなければ本番環境で発生しなさそう?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?