Rails开发细节(五)Migrations 数据迁移2013-12-111.简介在rails中用migration可以很方便的管理数据库的结构。可以创建数据库,创建表,删除表,添加字段,删除字段,整理数据。migration就是一系列的class,这些类都继承了ActiveRecord::Migration类。
class CreateProducts < ActiveRecord::Migration def up create_table :products do |t| t.string :name t.column :description, :text t.timestamps end enddef down drop_table :products endend
上面就是一个migration例子。up方法中的代码会在rake db:migrate之后执行。down方法中的代码会在rake db:rollback之后执行。t.timestamps会自动产生created_at和updated_at列。还可以进行表结构修改。
class AddReceiveNewsletterToUsers < ActiveRecord::Migration def up change_table :users do |t| t.boolean :receive_newsletter, :default => falseend User.update_all ["receive_newsletter = ?", true] end def down remove_column :users, :receive_newsletter end end
rails3.1之后产生了一个新的方法change,主要用来创建表和列,不用写一对up和down了,使用rake db:rollback回滚的时候数据库不用down方法也知道如何做了。1.1.migration提供了很多的方法add_columnadd_indexchange_columnchange_tablecreate_tabledrop_tableremove_columnremove_indexrename_column如果想回滚migration对数据库造成的改变,可以使用rake db:rollback命令。1.2.ActiveRecord支持的列类型:binary:boolean:date:datetime:decimal:float:integer:primary_key:string:text:time:timestamp