Using Active Record Migrations.

Cristian Benitez
3 min readNov 6, 2021


First we need to create our migration files, here I’m using a Rake commandment to accomplish this.

rake db:create_migration NAME=create_tableName
Two migration files created separately with “rake db:create_migration NAME=create_tableName

After running the above command, your db/migrate folder should create all your new migrations. Now let’s go ahead and make our models.. “In the context of an application, these classes are commonly referred to as models. Models can also be connected to other models; this is done by defining associations.” Make our new ruby files inside our models folder.

Create our model/class files

Once created, let’s have our classes inherit from ActiveRecord::Base (line 1 below). This is essentially giving our classes access to a few things in ActiveRecord.

A Game will have_many reviews. **has_many associations must use the plural term**
A Review belongs_to a game. **belongs_to associations must use the singular term**

The ‘has_many’ and ‘belongs_to’ are ActiveRecord macros given to us through this inheritance. It’s now time to add code to our ‘migration files’ that will essentially create these 2 tables and their associated relationship. Check out the ruby docs for more information on active-record associations. (

Creating ‘games’ table in migration file.

Stop and think for a second…could a game-review exist without a game? NO. So let’s make our game table first. The #change method was created when we created those migrations. Inside the method we are saying “create a table called games, and make 3 columns: title, price, and platform make them all strings.” Now that we have our games table, let’s make the reviews table it associates itself with.

Creating ‘reviews’ table in migration file, and adding its association to a game using game_id

Since a game has_many reviews, the reviews table will need to keep track of the games with a game_id key. This will match the ID of an actual game instance in the ‘games’ table. Once this is all setup, we can then run a command to migrate these tables to the database using “rake db:migrate”.

Now you can imagine we have our two tables: game and review, inside our database, but what about the actual value of the data itself? Is there a way to add our own information? Yes!

Using active record macros gives us methods like, #create and #destroy_all. Here we are creating two games and two reviews. Each game and review have their own IDs, but each review has a game_id that correlates to the actual ID of the game it belongs to. Now if we try and type ‘rake console’ we can see our data and how we can work with it.

Showing different “Read” actions.

Inside our rake console, we can try Game.all to get all the games, and will give you an array of reviews associated to that game. The text in purple that starts with “SELECT” is SQL doing its duty under the hood.



Cristian Benitez