Using the Rails Console to Update and Delete Database Records
Learn how to use the Rails console to update and delete items in the database.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that you know how to create database records, let's work around a little bit with update and delete.

Get into your console with the command rails c

Next, let's run the database query Project.all

This will bring up all the records in the database in the projects table.

large

The type of object it brings back is an ActiveRecord collection that contains an array of objects, which in this case, are projects with the attributes title, description, percent_complete, created_at and updated_at. If you look closely, you will see there are three dots at the end, and this means, there are more records in the database but for the sake of efficiency Rails truncates the output. This is a sensible way of displaying records because there can be thousands of records in a production database, and you obviously don't want all of them to get listed.

A common query that you'll use is Project.count to know the number of records in a database. You can also see just the last record with the command Project.last You can even assign this command to a variable, and call the variable every time you want to access the last record. For example, you can say
p = Project.last and then type p to see the last record.

I can also use this variable to update this record. For example, p.update!(title: "My Cool Title"), and this command will update the title in my last record.

large

If you notice, this function returned the value true, so we know that the update was successful. You can also see the Update query called by the ActiveRecord method to update this record.

Similarly, I can delete the record by typing p.delete. To verify, you can run Project.count and this will show one record less this time.

However, if you type p, you can still see the same record because this variable is just a reference to that object, and not that object itself. This information will be available in the p variable as long as I keep this session open.

Now that you know to create, update and delete, let's look at some more complex code in the next video.