DB curiosity: ORM to Active Record

aaron feingold
3 min readJan 24, 2021


I’m assuming if you’re coming to this article from my last, you felt there was a little bit of unresolved information. Can you elaborate a little bit on this ORM thing? Why all this secrecy behind ActiveRecord?

An Object-Relation Mapper allows object-oriented programming to use an SQL database, which is not object oriented. If you are trying to create a program to store object values, using this system, the data is converted back and forth; its persistent. The basic “mapping” concept boils down to this very simply…think:

Class → Database Table

Instances → Table Rows

attr_accessor → Column name

**Keep in mind, the classes are mapped to tables within the database — there can be many tables in the db. That’s pretty much our our end goal here: to be able to create relations or associations between the various tables.

Although it sounded a little odd at first, it makes sense: the Class is pluralized for the table name. So, if you were trying to build an app that replicates the Music World: you could make a Musician class; and, your table would be named “musicians”. Think of a class as a model of some thing — maybe real, maybe theoretical. One of those things, that’s an instance; we’re keeping a record of our objects. Only get this: we’re not actually saving the objects in our db: we’re using those “attr_accessors” to create a new row in a table. Attr is basically short of “attribute”. Consider:

good_food = Meal.new(“Bacon”, “Meat”, “Delicious”)good_food.name# => “Bacon”good_food.category# => “Meat”good_food.note# => “Delicious”

Our attributes here are, as you guessed: name, category, and note. This what the SQL looks like:

INSERT INTO meals (name, category, note) VALUES (“Bacon”, “Meat”, “Delicious”)

Note: we are only making a new instance when we call #new on a class. Its representation in the db has not yet been saved, however, as #save is another method, which takes the attributes, and inserts it into a row through an established connection. We do not necessarily have to save the object to the db the moment it’s created, ie. initialized. Nevertheless, when saved to the db, that’s when we create the primary key in the id column, which the db assigns to the new insertion, and our save method will now allow us to call //good_food.id//, for instance. Consider now this:

So ok, you’re probably thinking this looks like a lot of repetition, having to go through all this every time we want to convert objects into our tables. In enters ActiveRecord. Suddenly, this gem gives us tons of mechanics and methods simply like this:

Class Meals < ActiveRecord::Base

Now enters Rake Tasks, migrations, seeds, and whole slew of methods for us to run SQL on db with a trackable level of version control. That will be our next discussion: running migrations basics.




aaron feingold

web developer making apps for people with appetite