2
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.

外部キーに指定されているカラムのデータを削除しようとしたときのメモ

Posted at

外部キーに指定されているデータをdestroyしようとしたところ、エラーが出てdestroyできなかったのでメモ。

やろうとしたこと

メモアプリで、メモに紐づくタグをグループ化するフォルダーのデータを削除しようとした。

問題点

エラー(外部キーに指定されたデータを削除できないよ、的なメッセージ)

前提

メモアプリで、メモにタグを紐づけている
フォルダにより、タグをグループできる。
削除しようとしたデータは、フォルダのデータ。

フォルダテーブルのデータ
mysql> select * from folders;
+----+------------+---------+---------------------+---------------------+
| id | name       | user_id | created_at          | updated_at          |
+----+------------+---------+---------------------+---------------------+
|  3 | Tag_group1 |       1 | 2020-03-31 15:25:48 | 2020-03-31 15:25:48 |
+----+------------+---------+---------------------+---------------------+
タグテーブルのデータ
mysql> select * from tags;
+----+-----------+---------+---------------------+---------------------+-----------+
| id | name      | user_id | created_at          | updated_at          | folder_id |
+----+-----------+---------+---------------------+---------------------+-----------+
|  3 | test_tag1 |       1 | 2020-03-31 13:57:45 | 2020-03-31 13:57:45 |      NULL |
|  4 | test_tag2 |       1 | 2020-03-31 13:58:03 | 2020-03-31 13:58:03 |      NULL |
+----+-----------+---------+---------------------+---------------------+-----------+
2 rows in set (0.00 sec)

タグテーブルの定義
mysql> desc tags;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | NO   | UNI | NULL    |                |
| user_id    | bigint(20)   | YES  | MUL | NULL    |                |
| created_at | datetime     | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
| folder_id  | bigint(20)   | YES  | MUL | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

→ タグテーブルでは、削除しようとしたフォルダーのIDを外部キーとして持つ

解決方法

→ タグテーブルでもつ外部キーの値を先に削除する。

app/controllers/folders_controller.rb
  def destroy
    @folder = Folder.find(params[:id])
    @tags = Tag.where(folder_id: @folder.id)
    @tags.each do |tag|
      tag.update_column(:folder_id, nil)
    end
    @folder.destroy
  end

データの更新方法

Instance.update_column(:column_name value)
2
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
2
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?