Migrations are a feature of Active record that helps you to update the database schema by using Ruby DSL instead of SQL queries.
The above image represents a typical migration file of a
Product model with attributes
Here the above script generates a table called ‘
products‘ and a
string type column called
'name' & a
text type column called
Migrations files are stored in the
db/migrate/timestampvalue_createxxx_xxxx_xxx & in this format
Here if you look the migrations file name is in format of YYYYMMDDHHSSSS_create_products.rb, the first sequence is the timestamps, when you run
rake db:migrate the migrations files are executed on the basis of timestamps.
For example the above filename ie
'20180327061129_create_products.rb' should define the class
'CreateProducts' which would be camel cased.
Now let’s try adding a part number to every product. So let’s write a generator script provided by the rails for creating migration ie
And it will create another migration in the app*/db/ directory another migration file as below
And the contents of the migration file is
Here what it says is add a column named
'part_number' of a type string to the products table. In a migration file, you’re not restricted to add just one column, instead of that you can add multiple columns as per the below code
rails generate migration AddDetailsToProducts part_quantity:string part_number:string