Method: ActiveRecord::Persistence#reload
- Defined in:
- activerecord/lib/active_record/persistence.rb
#reload(options = nil) ⇒ Object
Reloads the record from the database.
This method finds the record by its primary key (which could be assigned manually) and modifies the receiver in-place:
account = Account.new
# => #<Account id: nil, email: nil>
account.id = 1
account.reload
# Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]]
# => #<Account id: 1, email: '[email protected]'>
Attributes are reloaded from the database, and caches busted, in particular the associations cache and the QueryCache.
If the record no longer exists in the database ActiveRecord::RecordNotFound is raised. Otherwise, in addition to the in-place modification the method returns self for convenience.
The optional :lock flag option allows you to lock the reloaded record:
reload(lock: true) # reload with pessimistic locking
Reloading is commonly used in test suites to test something is actually written to the database, or when some action modifies the corresponding row in the database but not the object in memory:
assert account.deposit!(25)
assert_equal 25, account.credit # check it is updated in memory
assert_equal 25, account.reload.credit # check it is also persisted
Another common use case is optimistic locking handling:
def with_optimistic_retry
begin
yield
rescue ActiveRecord::StaleObjectError
begin
# Reload lock_version in particular.
reload
rescue ActiveRecord::RecordNotFound
# If the record is gone there is nothing to do.
else
retry
end
end
end
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 |
# File 'activerecord/lib/active_record/persistence.rb', line 742 def reload( = nil) self.class.connection_pool.clear_query_cache fresh_object = if apply_scoping?() _find_record(( || {}).merge(all_queries: true)) else self.class.unscoped { _find_record() } end @association_cache = fresh_object.instance_variable_get(:@association_cache) @association_cache.each_value { |association| association.owner = self } @attributes = fresh_object.instance_variable_get(:@attributes) @new_record = false @previously_new_record = false self end |