Difference between update and update_attributes
Asked Answered
L

5

16

In Rails 5, what is the difference between update and update_attributes methods. I'm seeing the following results for both the methods

  1. Returns true/false
  2. Checking for active record validation
  3. Call backs are triggered

and also regarding update method a new thing was introduced in active record relation. I'm not able to understand it. What is the difference?

Moreover are we using update_attributes in Rails 5. It's not there in active record documentation.

I'm confused with all update methods. I need clarity

Levkas answered 18/12, 2018 at 9:49 Comment(0)
T
15

As of Rails 4.0.2, #update returns false if the update failed. Before Rails 4.0.2, #update returned the object that got updated. The main difference therefore was the return value. After this change, #update_attributes is just an alias of #update.

As of Rails 6.0, #update_attributes is deprecated in favor of #update.

Threesquare answered 29/5, 2019 at 23:58 Comment(1)
Deprecate update_attributes/! in favor of update/!. in Rails 6. So meaning update/! will no longer an alias of update_attributes. Correct me if I'm understanding is wrong.Njord
P
2

From the rails 5 files it seems to me update can be used to update multiple objects(array of records) but update_attributes only work on single records otherwise both are same

From rails core files for update_attributes:

Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. Also note that

  • Validation is skipped.
  • \Callbacks are invoked.
  • updated_at/updated_on column is updated if that column is available.
  • Updates all the attributes that are dirty in this object.

This method raises an ActiveRecord::ActiveRecordError if the attribute is marked as readonly.

def update_attribute(name, value)
  name = name.to_s
  verify_readonly_attribute(name)
  public_send("#{name}=", value)

  save(validate: false)
end

For Update

Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

==== Parameters

  • +id+ - This should be the id or an array of ids to be updated.
  • +attributes+ - This should be a hash of attributes or an array of hashes.

==== Examples

# Updates one record Person.update(15, user_name: "Samuel", group: "expert")

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

# Updates multiple records from the result of a relation people = Person.where(group: "expert") people.update(group: "masters")

Note: Updating a large number of records will run an UPDATE query for each record, which may cause a performance issue. When running callbacks is not needed for each record update, it is preferred to use {update_all}[rdoc-ref:Relation#update_all] for updating all records in a single query.

def update(id, attributes)
  if id.is_a?(Array)
    id.map { |one_id| find(one_id) }.each_with_index { |object, idx|
      object.update(attributes[idx])
    }
  else
    if ActiveRecord::Base === id
      raise ArgumentError,
        "You are passing an instance of ActiveRecord::Base to `update`. " \
        "Please pass the id of the object by calling `.id`."
    end
    object = find(id)
    object.update(attributes)
    object
  end
end
Pardon answered 18/12, 2018 at 13:2 Comment(2)
Validations are not skipped in rails 5 updated_attributesLevkas
You provided documentation for update_attribute, not update_attributesLeticialetisha
R
0

When we are working with update_column that time update is done on the database level there is no any contact with the rails ORM so whatever logic we have implemented like callbacks and validations all will be waste and wont be useful as this is going to be bypassed.

Rustproof answered 29/1, 2019 at 6:52 Comment(0)
D
-1

I found this article explained really well in just 30 seconds.

.update

Use update when you want to return false, for example in an if/else:

if record.update(params)
  display_success
else
  react_to_problem
end

.update!

Use update! when you want an error (for example: to avoid erroring silently, which could be very bad if an error was unexpected and you needed to know about it to fix it!):

  record.update!(params) # raises is invalid
Dutiful answered 29/5, 2021 at 4:49 Comment(0)
H
-4

'update' respects the validation rules on model, while 'update_attributes' ignores validations.

Heckle answered 20/3, 2022 at 12:9 Comment(1)
Both methods respect validation, I think you're confused with update_attributeJuxtaposition

© 2022 - 2024 — McMap. All rights reserved.