instance method
reload
Ruby on Rails edge
Since v3.0.20Signature
reload(options = nil)
Replaces the record attributes with the current values in 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: 'account@example.com'>
Internal state managed by Active Record, such as the associations cache is reset accordingly, but custom instance variables are left as-is.
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
Parameters
-
optionsopt = nil
Source
# File activerecord/lib/active_record/persistence.rb, line 779
def reload(options = nil)
self.class.connection_pool.clear_query_cache
fresh_object = if apply_scoping?(options)
_find_record((options || {}).merge(all_queries: true))
else
self.class.unscoped { _find_record(options) }
end
@association_cache = fresh_object.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
Defined in activerecord/lib/active_record/persistence.rb line 779
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Persistence