Rails Cheat Sheet: Models and Migrations

Aicha Diallo
4 min readOct 24, 2019

--

There is some truth to the adage that the best programmers tend to be lazy. This usually, undesirable trait actually, oddly has a positive connotation in code world. What it actually means is that Developers avoid repetitive, monotonous and extremely verbose code. Part of this also means having shortcuts available so that you can efficiently develop your software in order to achieve maximum productivity.

Ruby on Rails is a great database-backed web-application framework to have shortcuts for as they will come in very handy. As such, this resource is intended to help you achieve a simple models, tables and migrations for Ruby on Rails. This is not a cheat sheet for creating a full CRUD app and implementing RESTful conventions, but rather the methods needed to create the models and implement migrations accordingly.

If you are not familiar with Ruby on Rails, refer to the rails homepage for more information. This Ruby on Rails guide is also a great resource to help you get familiarized with this popular framework.

Now….

1) Setup-Create a new table in Rails

To generate a new Rails application, begin by entering in the terminal:

rails new Product  (*product here is an example, you would use your own name based on what you are building)

Alternatively, you can create the model which does a similar action as above (still in the terminal ):

rails generate model Product name:stringor rails g model Product name:string

The above model creation resulted and autogenerated this migration table below:

class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.timestamps null: false
end
end
end

With the product example above, remember that is the space holder for the actual name of your model. Models are singularized and not plural.

During the creation of a model, you can use as many or as little descriptive attributes for your model as you would like. As demonstrated in the first example above, the model we are creating only had a “name” attribute. Unlike the one below which is much more detailed:

rails g model Product name:string count:integer description:text popularity:float available:boolean availableSince:datetime 

In the model above, we added a bit more description in the creation process of the Model which resulted(autogenerated) this migration:

class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.integer :count
t.text :description
t.float :popularity
t.boolean :available
t.datetime :availableSince

2) Rails db:migrate

Once you have finalized your model and their attributes, if you are satisfied with your content and have no changes to make, in the command line, run:

rails db:migrate

This step allows you to clearly define and implement your database schema, making it possible to synchronize your data with code.

3) Add a column

Uh oh but wait a minute! To err is human and you DO have a change to make after all. But you have already run rails db:migrate!! What now?

Fret now, there are a few options available to resolve this issue.

You can either run:

rails db:rollback

This action enables you to take down the migration you just did and re-adjust it accordingly. Alternatively, you can adjust the table that you created by running the following in the command line:

rails g migration AddKeywordsSizeToProduct keywords:string size:string

Resulting the following autogenerated table:

class AddKeywordsSizeToProduct < ActiveRecord::Migration
def change
add_column :products, :keywords, :string
add_column :products, :size, :string
end
end

Once you have adjusted your model accordingly, once again run rails db:migrate to push up and migrate your updated table.

4) Remove a column

If you made a mistake and would like to remove a column you had previously created, you would do the following command:

rails g migration RemoveKeywordsFromProduct keywords

Here is what the table would look like:

class RemoveKeywordsFromProduct < ActiveRecord::Migration
def change
remove_column :products, :keywords, :string
end
end

5) Renaming a column

rails g migration RenameProductPopularityToRanking

The migration would look like this:

class RenameProductPopularityToRanking < ActiveRecord::Migration
def change
rename_column :products, :popularity, :ranking
end
end

6) Rails migration to change a column type

In your project, it is a common that you start with a model having a particular attribute and then you realize it needs another. For example, if you think you should have stored a column as a string when it actually should be an integer.

The code that we need for this is:

change_column :table_name, :column_name, :new_type

Resulting migration:

class ChangeProductPopularity < ActiveRecord::Migration
def change
change_column :products, :ranking, :decimal
end
end

7) Running migrations

Once you have finished building all your models and migrations, to update the database, finish the process by once again running:

rails db:migrate

Rails db:migrate:status allows you to see which tables you have up or down. When it isup this lets Rails know what to do when handling a db:migrate and down lets Rails know what to do when handling a db:rollback.

Et voila! I hope this is resourceful. After doing this many times over, you will have the muscle memory to no longer need a cheat sheet like this. Neat!

--

--