Method summary to update multiple columns [Ruby on Rails]

Rails has multiple methods to update multiple columns at the same time, so I've summarized the differences.


assign_attributes

Features </ strong>

  • DB is not saved.
  • alias is attributes =

Usage </ strong> (if you have a table called User)

user = User.first
user.assign_attributes(family_name: "foo", given_name: "bar")
user.save

#attribute=in the case of
user.attributes = { family_name: "foo", given_name: "bar" }

It is not saved, so you need to call save.


update_attributes

Features </ strong>

  • Saved in DB.
  • alias is update
  • Validation checks and callback calls are also performed.
  • Returns whether saving is true or false.

Usage example </ strong>

user = User.first
user.update_attributes(family_name: "foo", given_name: "bar")

#For update
user.update(family_name: "foo", given_name: "bar")

There is no need to call save separately.


update_attributes!

Features </ strong>

  • If saving fails, an exception will be thrown.
  • alias is update!

Usage example </ strong>

user = User.first
user.update_attributes!(family_name: "foo", given_name: "bar")

#update!in the case of
user.update!(family_name: "foo", given_name: "bar")

The way to return the result is different from update_attributes.


update_columns

Features </ strong>

  • The fastest update speed because it accesses the database directly.
  • No validation check or callback call.
  • update_at is not updated.

Usage example </ strong>

user = User.first
user.update_columns(family_name: "foo", given_name: "bar")

Please note that there are no validation checks or callback calls.


reference https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attributes

Recommended Posts