Creating and Updating

Learn to create and update new and existing rows using active record

Names such as SQLite and MySQL emphasize that all access to a database is via the Structured Query Language (SQL). In most cases, Rails will take care of this for us, but that is completely at our discretion. As we’ll see, we can provide clauses or even entire SQL statements for the database to execute.

If we’re familiar with SQL already, take note of how Rails provides places for familiar clauses such as select, from, where, group by, and so on as you read this section. If we’re not already familiar with SQL, one of the strengths of Rails is that we can defer learning more about such things until we actually need to access the database at this level.

In this section, we’ll continue to work with the Order model from the Depot application as an example. We’ll be using Active Record methods to apply the four basic database operations: create, read, update, and delete.

Creating new rows

Given that Rails represents tables as classes and rows as objects, it follows that we create rows in a table by creating new objects of the appropriate class. We can create new objects representing rows in our orders table by calling in line 1. We can then fill in the values of the attributes, which correspond to columns in the database. Finally, we call the object’s save() method in line 6 to store the order back into the database. Without this call, the order would exist only in our local memory.

Get hands-on with 1200+ tech skills courses.