...

/

Locating and Traversing Records

Locating and Traversing Records

Get an overview of how we interact with the database to identify the relationships between different rows.

In the Depot application, LineItems have direct relationships to three other models: Cart, Order, and Product. Additionally, models can have indirect relationships mediated by resource objects. The relationship between Orders and Products through LineItems is an example of such a relationship.

All of this is made possible through IDs.

Identifying individual rows

Active Record classes correspond to tables in a database. Instances of a class correspond to the individual rows in a database table. Calling Order.find(1), for instance, returns an instance of an Order class containing the data in the row with the primary key of 1.

If we’re creating a new schema for a Rails application, we’ll probably want to go with the flow and let it add the id primary key column to all our tables. However, if we need to work with an existing schema, Active Record gives us a way of overriding the default name of the primary key for a table.

For example, we may be working with an existing legacy ...