Reading existing rows

Reading from a database involves first specifying which particular rows of data we are interested in. We’ll give Active Record some kind of criteria, and it will return objects containing data from the row(s) matching the criteria.

The most direct way of finding a row in a table is by specifying its primary key. Every model class supports the find() method, which takes one or more primary key values. If given just one primary key, it returns an object containing data for the corresponding row or throws an ActiveRecord::RecordNotFound exception. If given multiple primary key values, find() returns an array of the corresponding objects. Note that in this case, a RecordNotFound exception is raised if any of the IDs cannot be found. So, if the method returns without raising an error, the length of the resulting array will be equal to the number of IDs passed as parameters.

Get hands-on with 1200+ tech skills courses.