Retrieve all model objects of a particular type from the database

❮ Back Next ❯

In this step, you will learn how to retrieve all the records from a model database table and load those data into model objects.

Clear and re-seed the database with data by running these two commands in the terminal:

rails db:migrate:reset
rails db:seed

Launch the Rails console, so we can try out the Ruby code for retrieving data from the database:

rails console

To retrieve all the Person model objects from the database, enter this Ruby code into the console:

all_people = Person.all

Note that the SQL command in the output, SELECT "people".* FROM "people", indicates that all rows and columns were retrieved from the database table people. The all_people variable now references an array of Person objects (technically, it is a Relation, but it is sufficient to think of it as an array).

To iterate through the array of Person objects, printing the first_name of each object in turn, enter this Ruby code into the console:

all_people.each do |current_person|
  puts current_person.first_name
end

Note that the output of this code is a little confusing. If we scroll up and inspect the output immediately following the entered code, we will see the list of four first names. The confusing thing is that this output is followed by a long pretty-printed dump of the contents of the Person array. The reason for this dump is that the Rails console prints the value returned by the entered code, and in this case, the each method returns the entire Person array.

Also note that the names are sorted in the same order that they were created in the seeds.rb script.

To retrieve model objects sorted in a particular order, the all method can be replaced with order (see API docs here).

In the Rails console, enter this Ruby code to retrieve from the database all the Person objects sorted in ascending order first by last_name and second by first_name:

all_people_sorted = Person.order(:last_name, :first_name)

Note that SQL SELECT command mentioned in the output now includes the additional arguments, ORDER BY "people"."last_name" ASC, "people"."first_name" ASC, which indicates that the retrieved table rows are to be sorted in the specified order.

Print the name of each Person object (this time, formatted as “Last-name, First-name”) in the sorted array by entering this Ruby code:

all_people_sorted.each do |current_person|
  puts current_person.last_name + ", " + current_person.first_name
end

Note that the outputted list of four names is now sorted first by last_name and second by first_name.

Exit out of the Rails console:

exit

❮ Back Next ❯