Migrations in rails are basically used for executing DDL (Data Definition Language) statements. The main tasks of migrations are:
1. Creating tables
2. Updating Schemas
3. Altering tables
4. Dropping tables
Each migration works as a new version of database, so you can revert back to any version whenever you want. Initially when you start with an application there is nothing written on the schema and once you start creating migrations and running them, schema starts getting updated. So here I am guiding you to types of operations that are used most commonly used using migrations.
1. Creating a Table:
Rails is a very smart language so once you generate a model, it automatically knows that you want a migration to be built for creating a table so as soon as you run the generate model command like this, it will create its migration too.
$ rails g model Article title:string description:string
# => Output
So the migration of creating table will look something like:
class CreateArticles < ActiveRecord::Migration
create_table :articles do |t|
t.timestamps null: false
if you have forgotten anything during creation of the model, you can add those fields in the migration and then you can run the migration using
Once you run the migration it will create a table named articles with two columns title and description of string type.
If you closely look at the name of the migration file you will notice that the name is actually of the type YYYYMMDDHHMMSS_create_articles.rb, so the name of the migration has actually the timestamp and the task it performs. As per the naming conventions of rails the class name for this migration will be CreateArticles by default.
Now lets see the syntax of creating the model, it includes the Model name and the fields names seperated by space and there datatype is also there beside the fields name separated by colon(:).
Thus the syntax of this can be written as
rails g model ModelName field1:datatype field2:datatype field3:datatype