使用数据移植修改表
当然,开发者总想通过一种简单的方式来管理数据库的表。和前面的任务一样,你只需要创建一个新的数据移植脚本,就可以完成管理数据表了。举个例子来说,假如你像增加一个city列到contacts表中:
%>ruby script/generate migration modify_contacts_add_city exists db/migrate create db/migrate/002_modify_contacts_add_city.rb
打开002_modify_contacts_add_city.rb文件并对它进行修改,如下所示:
class ModifyContactsAddCity < ActiveRecord::Migration def self.up add_column :contacts, :city, :string end def self.down remove_column :contacts, :city end end
再次执行describe contacts命令,你将看到city列已经被增加到这个表中了!
mysql> describe contacts; +----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | | email | varchar(255) | YES | | NULL | | | birthday | date | YES | | NULL | | | city | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)
注意,我还执行了down方法;它将移除这个city列。为了删除这个列,只需回滚数据移植到001版本即可,如下所示:
C:\ruby\addressbook>rake db:migrate VERSION=001 (in C:/ruby/addressbook) == ModifyContactsAddCity: reverting =========================== -- remove_column(:contacts, :city) -> 0.1720s == ModifyContactsAddCity: reverted (0.1720s) ==================
结论
这个指南只是介绍给了你Rails的数据移植功能的冰山一角;它不仅支持MySQL,还支持目前市面上的大多数数据库,诸如SQLite、PostgreSQL、SQL Server和Oracle。如果你想了解更多这个精彩工具的功能,可以去查看Rails的官方站点的migrations documentation(http://api.rubyonrails.org/classes/ActiveRecord/Migration.html)。尽管数据库移植是Rails特有的一个功能,there's nothing to prevent you from quickly creating a solution for managing MySQL no matter what web development language you settle upon.