reload
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (38)
- 4.1.8 (1)
- 4.2.1 (0)
- 4.2.7 (1)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
reload(options = nil)
public
Reloads the record from the database.
This method finds 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'>
Attributes are reloaded from the database, and caches busted, in particular the associations cache.
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