Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord-update/active_record/base.rb

Class Method Summary collapse

Class Method Details

.update_records(records) ⇒ ActiveRecord::Update::Result

Updates a list of records in a single batch.

This is more efficient than calling ‘ActiveRecord::Base#save` multiple times.

  • Only records that have changed will be updated

  • All new records will be ignored

  • Validations will be performed for all the records

  • Only the records for which the validations pass will be updated

  • The union of the changed attributes for all the records will be updated

  • The ‘updated_at` attribute will be updated for all the records that where updated

  • All the given records should be of the same type and the same type as the class this method is called on

  • If the model is using optimistic locking, that is honored

Examples:

Model.update_records(array_of_models)

Parameters:

Returns:

See Also:



61
62
63
64
65
66
67
# File 'lib/activerecord-update/active_record/base.rb', line 61

def update_records(records)
  _update_records(
    records,
    raise_on_validation_failure: false,
    raise_on_stale_objects: false
  )
end

.update_records!(records) ⇒ ActiveRecord::Update::Result

Updates a list of records in a single batch.

This is more efficient than calling ‘ActiveRecord::Base#save` multiple times.

  • Only records that have changed will be updated

  • All new records will be ignored

  • Validations will be performed for all the records

  • Only the records for which the validations pass will be updated

  • The union of the changed attributes for all the records will be updated

  • The ‘updated_at` attribute will be updated for all the records that where updated

  • All the given records should be of the same type and the same type as the class this method is called on

  • If the model is using optimistic locking, that is honored

The difference compared to update_records is that this method will raise on validation failures. It will pick the first failing record and raise the error based that record’s failing validations.

If an ‘ActiveRecord::RecordInvalid` error is raised none of the records will be updated, including the valid records.

If an ‘ActiveRecord::StaleObjectError` error is raised, some of the records might have been updated and is reflected in the Update::Result#ids and Update::Result#stale_objects attributes on the return value.

Examples:

Model.update_records(array_of_models)

Parameters:

Returns:

Raises:

  • (ActiveRecord::RecordInvalid)

    if any records failed to validate

  • (ActiveRecord::StaleObjectError)

    if optimistic locking is enabled and there were stale objects

See Also:



90
91
92
93
94
95
96
# File 'lib/activerecord-update/active_record/base.rb', line 90

def update_records!(records)
  _update_records(
    records,
    raise_on_validation_failure: true,
    raise_on_stale_objects: true
  )
end