instance method reload

Ruby on Rails 8.0.4

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

reload(options = nil)

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: 'account@example.com'>

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

Parameters

options opt = nil
Source
# File activerecord/lib/active_record/persistence.rb, line 742
    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.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

Defined in activerecord/lib/active_record/persistence.rb line 742 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Persistence

Type at least 2 characters to search.

↑↓ navigate · open · esc close