🖥
Ruby on #Rails - Model#delete does not work? can not delete records?
x User.delete(name: 'Alice')
o User.where(name: 'Alice').destroy_all
User.delete class method is not like "where" style
User.delete class mathod takes id or ids in arguments
User.delete(name: 'Alice')
User Destroy (0.7ms) DELETE FROM `users` WHERE `users`.`id` = NULL
=> 0
Specify id
User.delete(24)
User Destroy (2.8ms) DELETE FROM `users` WHERE `users`.`id` = 24
=> 1
Specify ids
User.delete([25,26])
User Destroy (5.0ms) DELETE FROM `users` WHERE `users`.`id` IN (25, 26)
=> 2
return value is "deleted recourds" num
btw User.destory class method not exists
User.destroy(name: 'Alice')
# ActiveRecord::RecordNotFound: Couldn't find User with 'id'={:name=>"Alice"}
You must find user instance and delete
But delete not consider abount association
User.find_by(name: 'Alice').delete
# User Load (0.9ms) SELECT `users`.* FROM `users` WHERE `users`.`name` = 'Alice' LIMIT 1
# User Destroy (3.1ms) DELETE FROM `users` WHERE `users`.`id` = 12
You must use "destory" usally because "destroy" take care abount association
User.find_by(name: 'Alice').destroy
# User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`name` = 'Alice' LIMIT 1
# (0.4ms) BEGIN
# User Destroy (0.8ms) DELETE FROM `users` WHERE `users`.`id` = 23
# (1.5ms) COMMIT
You can delete multiple records with "where" and "delete_all"
[79] pry(main)> User.where(name: 'Alice').delete_all
User Destroy (3.7ms) DELETE FROM `users` WHERE `users`.`name` = 'Alice'
=> 2
You can delete multiple records with "where" and "destroy_all"
[82] pry(main)> User.where(name: 'Alice').destroy_all
User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`name` = 'Alice'
(0.7ms) BEGIN
User Destroy (3.3ms) DELETE FROM `users` WHERE `users`.`id` = 21
(6.1ms) COMMIT
(0.6ms) BEGIN
User Destroy (0.9ms) DELETE FROM `users` WHERE `users`.`id` = 22
(3.4ms) COMMIT
Original by Github issue
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-12-28
Discussion