destroyメソッドとは
destroyは、テーブルにあるデータを一件削除するメソッドです。
*ただし、関連しているモデルがあればその関連しているデータも削除してしまいます。
モデル名.find(id).destroy
参考例
[11] pry(main)> User.find(8).destroy
User Load (1.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 8 LIMIT 1
TRANSACTION (0.3ms) BEGIN
Tweet Load (0.7ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`user_id` = 8
User Destroy (1.4ms) DELETE FROM `users` WHERE `users`.`id` = 8
TRANSACTION (1.8ms) COMMIT
=> #<User:0x00000001165d9d20 id: 8, name: "加藤", age: 23, gender: "women", created_at: Mon, 29 Nov 2021 19:39:04.516129000 UTC +00:00, updated_at: Mon, 29 Nov 2021 19:39:04.516129000 UTC +00:00>
上記の例は、idが8のレコードを削除しています。
destroy_allメソッドとは
destroyと違い、destroy_allは複数のデータを一括削除する時に使用するメソッドです。
*ただし、destroyと同じく関連するデータも削除してしまいます。
モデル名.where(カラム).destroy_all
参考例
[13] pry(main)> User.where(id: 9..10).destroy_all
User Load (1.1ms) SELECT `users`.* FROM `users` WHERE `users`.`id` BETWEEN 9 AND 10
TRANSACTION (0.1ms) BEGIN
Tweet Load (0.3ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`user_id` = 9
User Destroy (5.0ms) DELETE FROM `users` WHERE `users`.`id` = 9
TRANSACTION (2.6ms) COMMIT
TRANSACTION (0.1ms) BEGIN
Tweet Load (0.3ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`user_id` = 10
User Destroy (0.5ms) DELETE FROM `users` WHERE `users`.`id` = 10
TRANSACTION (0.7ms) COMMIT
=> [#<User:0x000000012005bd30 id: 9, name: "高橋", age: 23, gender: "women", created_at: Mon, 29 Nov 2021 19:39:08.848516000 UTC +00:00, updated_at: Mon, 29 Nov 2021 19:39:08.848516000 UTC +00:00>,
#<User:0x000000012005bc68 id: 10, name: "山田", age: 23, gender: "women", created_at: Mon, 29 Nov 2021 19:39:24.145088000 UTC +00:00, updated_at: Mon, 29 Nov 2021 19:39:24.145088000 UTC +00:00>]
上記の例では、idが9,10のデータを一括削除しています。
[16] pry(main)> User.where(age: 23).destroy_all
User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`age` = 23
TRANSACTION (0.2ms) BEGIN
Tweet Load (0.6ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`user_id` = 11
User Destroy (2.8ms) DELETE FROM `users` WHERE `users`.`id` = 11
TRANSACTION (1.1ms) COMMIT
TRANSACTION (0.2ms) BEGIN
Tweet Load (0.4ms) SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`user_id` = 12
User Destroy (0.3ms) DELETE FROM `users` WHERE `users`.`id` = 12
TRANSACTION (0.5ms) COMMIT
=> [#<User:0x00000001068366f0 id: 11, name: "山田", age: 23, gender: "women", created_at: Mon, 29 Nov 2021 20:00:05.917480000 UTC +00:00, updated_at: Mon, 29 Nov 2021 20:00:05.917480000 UTC +00:00>,
#<User:0x0000000106836628 id: 12, name: "加藤", age: 23, gender: "women", created_at: Mon, 29 Nov 2021 20:00:09.515207000 UTC +00:00, updated_at: Mon, 29 Nov 2021 20:00:09.515207000 UTC +00:00>]
上記の例では、ageが23のデータを全て削除しています。