Record — JazzRecord JavaScript ORM Documentation
Docs Sections
The Record class is the means for interacting with individual rows from the database, and most interaction with data itself occurs through manipulation of Record instances.
NOTE: Record should only be instantiated by calls to the corresponding
Modelinstance, not constructed in your application code directly. To create a new Record, call the appropriate model'snewRecord()method orcreate()method.
Most of the work with records involves loading records from the database, changing their properties, and saving them back down in the modified state. JazzRecord makes short work of this.
After creating a new record object or fetching one with a model's finder method, you are given an object whose immediate properties represent the data stored in the matching columns of the model's table. Setting the values of these properties and then calling save() on the record object will result in a SQL INSERT or UPDATE statement, based on whether or not an ID exists on the record object.
Automatic Association Loading
One of the main features of JazzRecord is that it preloads any associated records automatically when first loading the primary record. What this means to you is that you won't have to make successive calls to the various models of your application to get at data related to the first record you were dealing with.
Instead of the following lines of code
var person = Person.first();
var hisVehicles = Vehicle.findAllBy("person_id", person.id);
var firstMake = hisVehicles[0].make;
You can write
var firstMake = Person.first().vehicles[0].make;
Which is quite a bit shorter.
JazzRecord has the ability to automatically associate records with one another to automatically load them on find:
//buying our first person a new car
var brandNewCar = Vehicle.create({make: "Infiniti", model: "FX35", person_id: 1});
//now the dude's "fresh whip" is part of the vehicles array!
var freshWhip = Person.first().vehicle;
console.log(freshWhip.model);
//it's an FX35, of course
If you want to reload a record to reset its data and obtain newly-assigned associations which may have become associated by assignments elsewhere in the app, call its reload() method.
Saving Records
There are a two methods for updating the data of a record:
save()Performs anINSERTorUPDATEquery and saves down all of the first-order properties of the primary record, meaning all data pertaining to columns directly on the primary record.updateAttribute(colName, value)sets and saves a single property of the primary record.
Calling save() will also iterate over all second-order properties [read: associated record objects] and save their data first before saving the primary record. This allows for automatic linking and unlinking of associations, a powerful addition to the library.
All 4 types of association relationships are iterated over, meaning records who have foreign records belonging to them or records which the current record belongs to will work with this. When saving a record, any objects it associates with will be saved first. This allows you to re-associate different records from those which were associated at the time the primary record was loaded, and still retain appropriate linkage on save.
Any formerly-associated records which are replaced by new ones will be saved with no ID column pointing to the current record, and any newly-associated records will have this ID added automatically.
Deleting Records
Record objects also have a destroy() method, which will perform a DELETE query on the database and remove the ID property from the object. It will not remove the object itself from memory, and will not currently dissociate associated objects.
Future versions of the library will perform this convenience, which means no more manual updating of directly-associated records.
Dirty Records
Records objects have a feature known in Rails 2.1 as "dirty objects". Currently available in JazzRecord there is a single method isChanged() which returns a boolean value based on whether the records's values have changed since it was last saved. This does not incur a database hit which is nice.
Future versions of JazzRecord will implement a changedColumns() method which returns an array of all changed column names, and an oldValue() method which takes a column name as a parameter and returns the previously-saved value, all without incurring another hit on the database.
If you want to revert a record object to its original state without incurring a hit on the database, call its revert() method.
Going Deeper
load(assocName, depth)
The Record class provides a method called load(), which will load associated records which were not loaded on an object due to depth-loading rules. This method takes an association name (not the column name) as a string parameter, and takes an optional depth parameter which will determine how deep to load the association.
This method will load either single-object associations or collections (arrays).
Example:
//cause only the person's 1st-order properties to load
var homeboy = Person.first({depth: 0});
//obtain homeboy's list of vehicles
var vehicles = homeboy.load("vehicles");
Calling load() on an already-loaded association will not incur a database hit, and so is a safe (if slightly wordier) means of ensuring you will always have association data you need.
Validation
Record objects will automatically call the validate() method (if one exists) provided in the definition of the Model object which spawned them. This method will be called before a save() call can be completed. If the record is invalid (because it breaks one of the business rules provided in the validate() method), strings explaining the reason will be available on the record's errors array.
There are default error messages provided with the built-in validation methods, and developers can override these as described in the validation section of the Model documentation.
A record can be checked manually for validity using the isValid() method, which returns a boolean as well as populates the errors array.
Callbacks
Record objects have a number of event hooks for triggering callbacks. See the Model documentation on callbacks for information on setting these up for all records of a given model.
Examples (invoking changes to status icon on a page):
var guy = Person.last();
guy.addEvent("update", function() {
$("status").className = "updating";
});
guy.addEvent("save", function() {
$("status").className = "saved";
});
guy.addEvent("destroy", function() {
console.log("Tragedy has struck our guy");
$("status").className = "deleted";
$("status").fade();
});
guy.name = "Guy";
guy.save();
//status icon flashes "updating status", then sets to "saved"
guy.destroy();
//status icon sets to "deleted", then fades out
//muahahaha









