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?

updateとupdate_allの使い分け

Posted at

環境

  • Ubuntu 20.4
  • Rails 5.2
  • Ruby 2.6

updateの使い方

updateメソッドはコントローラーの中で、findなどで1件だけ抽出したオブジェクトに対して、1件だけ更新するといった使い方が、基本的な使い方になります。

user.rb
user = User.find(1)
user.update(flg: "hoge")

updateの別名にupdate_attributesというのがあります。このように記述しても同じです。

user.rb
user = User.find(1)
user.update_attributes(flg: "hoge")

モデルの中でメソッドを作って、メソッドの中で更新させる使い方もできます。

user.rb
def update_user
    User.update(flg: "hoge").where(name: "tana")
end

しかし、モデルの中で使う場合は、update_attributesに置き換えて使うことができません。別名でありながらできません。

user.rb
def update_user
    User.update_attributes(flg: "hoge").where(name: "tana")
end

update_allの使い方

update_allはモデルの中で複数のデータを一括で更新する場合に利用します。更新データが1件しかなくても、update_allを使っても問題ありません。

user.rb
def update_user
    User.update_all(flg: "hoge").where(name: "tana")
end

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

user.rb
user = User.find(1)
user.update_all(flg: "hoge")

updateはコントローラーの中でオブジェクトに対して更新する使い方が主な使い方ですが、モデルのでupdate_allのように使うこともできます。

user.rb
def update_user
    User.update(flg: "hoge").where(name: "tana")
end

ただし、データ件数が1件であればいいのですが、データ件数が複数件存在する場合は、使うことが推奨されていません。決してエラーにはならないので、まったく使えないことはないのですが、普通は使いません。

なぜかといえば、更新するデータが10件あれば、updateのSQL文を10回生成して更新するからです。それに対し、update_allであれば、更新データが10件あっても、updateのSQL文は1回しか生成しません。

レスポンスに影響が出るため、効率的な使い方をしましょう。

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?