[Rails] Different update methods

Tags
Rails
Engineering
Created
Oct 8, 2023 11:08 PM
Edited
Oct 8, 2023
Description
update/update!/update_all/update_attributes/update_attribute/update_column(s)…

Common ones

update(attributes)

  • The most common one
  • Trigger everything like validation/callbacks and etc
# Updating one record:
Person.update(15, :user_name => 'Samuel', :group => 'expert')

# Updating multiple records:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

update!(attributes)

  • Calls save! internally, so it raises exception if errored
  • Others are the same as update

update_all

  • Does not trigger callbacks or validations
User.update_all max_login_attempts: 3, must_change_password: true

update_attributes

  • update_attributes triggers validations
  • Rails 6 deprecated update_attributes so just use update

update_attribute

  • update_attribute does not trigger validation

update_column and update_columns

  • Avoid using these because not all hooks are triggered

List of Update Methods

Rails 3

Rails 4

Source