0
1

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 1 year has passed since last update.

Ruby on #Rails - Model#delete does not work? can not delete records? delete class method take argument takes only ids. not like "where". Recommend use find_by / find / where and "destroy"

Last updated at Posted at 2019-12-28

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オープンチャットもご利用ください。

Twitter

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?