1. Introduction
Using migration in rails makes it easy to manage the structure of your database. You can create databases, create tables, delete tables, add fields, delete fields, and organize your data.
Migration is a series of classes, all of which inherit the Activerecord::migration class.
Class Createproducts < activerecord::migration
def up
create_table:p roducts do |t|
T.string:name
t.column:d escription,: Text
t.timestamps
end
def down
drop_table: Products
End
Above is a migration example. The code in the UP method will
Rake Db:migrate
executed afterwards.
The code in the Down method will
Rake Db:rollback
executed afterwards.
T.timestamps will automatically generate Created_at and Updated_at columns.
You can also make table structure modifications.
Class Addreceivenewslettertousers < activerecord::migration
def up
change_table:users do |t|
T.boolean:receive_newsletter,:d efault => false
end
User.update_all ["Receive_newsletter =?", True]
End
def down
remove_column:users,: receive_newsletter
End
rails3.1 creates a new method change, which is used primarily to create tables and columns, without writing a pair of up and down, and the database does not have to be down by using the Rake db:rollback rollback method.
1.1.migration offers a lot of ways
Add_column
Add_index
Change_column
Change_table
Create_table
Drop_table
Remove_column
Remove_index
Rename_column
If you want to roll back the migration changes to the database, you can use the Rake db:rollback command.
1.2.ActiveRecord Supported column types
: Binary
: Boolean
:d ate
:d Atetime
:d Ecimal
: float
: integer
:p Rimary_key
: string
: Text
: Time
: Timestamp