Persistence Details
Beyond basic CRUD operations, CQL Active Record models offer methods to understand and manage their persistence state.
This guide assumes you have a model defined, for example:
Checking Persistence Status
It's often useful to know if a model instance represents a record that already exists in the database or if it's a new record that hasn't been saved yet.
persisted?
persisted?
The persisted?
instance method returns true
if the record is considered to be saved in the database, and false
otherwise. Typically, this means the instance has a non-nil primary key (id
).
Use persisted?
to:
Differentiate between new and existing records in forms or views.
Decide whether an update or an insert operation is appropriate in more manual scenarios.
Conditionally execute logic based on whether a record is already in the database.
new_record?
(Conceptual / Alias for !persisted?
)
new_record?
(Conceptual / Alias for !persisted?
)Some ORMs provide a new_record?
method, which is typically the opposite of persisted?
. While CQL's core Persistence
module might not explicitly define new_record?
, you can achieve the same by checking !instance.persisted?
.
Reloading Records
Sometimes, the data for a record in your application might become stale if the corresponding row in the database has been changed by another process or a different part of your application. The reload!
method allows you to refresh an instance's attributes from the database.
reload!
reload!
The reload!
instance method fetches the latest data from the database for the current record (identified by its primary key) and updates the instance's attributes in place.
If the record no longer exists in the database (e.g., it was deleted by another process),
reload!
will typically raise aDB::NoResultsError
or a similarRecordNotFound
exception.
Use reload!
when:
You need to ensure you are working with the most up-to-date version of a record, especially before performing critical operations or displaying sensitive data.
You suspect an instance's state might be out of sync with the database due to concurrent operations.
Understanding these persistence details helps in managing the lifecycle and state of your Active Record model instances effectively.
Last updated
Was this helpful?