Retrieve All Model Objects of Specified Type from Database

❮❮ ❮ Back
Next ❯ ❯❯

Task

Steps

Reset and reseed database:

rails db:migrate:reset && rails db:seed

Launch Rails console:

rails console

Retrieve all Person objects from database:

all_people = Person.all

Iterate through array of Person objects, printing each’s first_name:

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

Retrieve all Person objects, sorted first by last_name, then by first_name:

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

Iterate through sorted array of Person objects, printing each’s last_name and first_name:

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

Exit Rails console:

exit

❮❮ ❮ Back
Next ❯ ❯❯