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?

deleteとdelete_allの使い分け

Posted at

はじめに

以前、「updateとupdate_allの使い分け」という記事を書いたが、今回はそれのdelete版です。deleteとdelete_allの使い方の違いは、updateとupdate_allの使い方の違いと似ています。しかし、まったく同じではないので注意が必要です。

削除をするメソットにはdeleteの他にdestroyもあります。deleteとdelete_allの関係は、destroyとdestroy_allの関係と同じです。

環境

  • Ubuntu 20.4
  • Rails 5.2
  • Ruby 2.6

delete、destroyの使い方

コントローラーの中で、findなどで1件だけ抽出したオブジェクトに対して、1件だけ削除するのが基本的な使い方です。

user.rb
user = User.find(1)
user.delete

destroyも使い方は同じです。

user.rb
user = User.find(1)
user.destroy

モデルの中でメソッドを作って、メソッドの中で削除することはできません。下記は共にエラーになります。

user.rb
def delete_user
    User.delete.where(name: "tana")
end

def destroy_user
    User.destroy.where(name: "tana")
end

delete_all、destroy_allの使い方

delete_all、destroy_allはモデルの中で複数のデータを一括で削除する場合に利用します。結果的に削除データが1件しかなくても、delete_all、destroy_allは流れてくれます。

削除データが複数件存在する場合、複数件数分のDeleteのSQL文が発行されるような稚拙なことはしません。ちゃんと、DeleteのSQL文1回で削除してくれます。

user.rb
def delete_user
    User.delete_all(flg: "hoge").where(name: "tana")
end

def destroy_user
    User.destroy_all(flg: "hoge").where(name: "tana")
end

コントローラーの中で、オブジェクトに対して削除させるような使い方はできません。共にエラーになります。

user.rb
user = User.find(1)
user.delete_all

user = User.find(1)
user.destroy_all
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?