`

Rails Migration参考

阅读更多

更新到最新版本:
rake db:migrate
重设数据库:
rake db:migrate VERSION=0


字段操作

1、字段类型
:binary, :boolean, :date, :datetime, :float, :integer, :string, :text, :time, :timestamp

2、add_column 添加字段
参数
:null => true or false 是否可为null
:limit => size  字段大小,通常是string字段的长度
:default => value 缺省的值

  1. add_column  :orders :placed_at :datetime :default  =>  Time .now  


3、rename_column 字段名修改
  1. class  RenameEmailColumn < ActiveRecord::Migration   
  2.        def   self .up   
  3.             rename_column  :orders :e_mail :customer_email   
  4.        end   
  5.       def   self .down   
  6.             rename_column  :orders :customer_email :e_mail   
  7.       end   
  8. end   

4、change_column  字段类型属性修改
  1. def   self .up   
  2.        change_column  :orders :order_type :string :null  =>  false   
  3. end   
  4. def   self .down   
  5.        change_column  :orders :order_type :integer   
  6. end   


表操作
  1. class  CreateOrderHistories < ActiveRecord::Migration   
  2.      def   self .up   
  3.         create_table  :order_histories   do   |t |   
  4.               t.column  :order_id :integer :null  =>  false   
  5.               t.column  :created_at :timestamp   
  6.               t.column  :notes :text   
  7.           end   
  8.      end   
  9.      def   self .down   
  10.         drop_table  :order_histories   
  11.      end   
  12. end   


重命名rename_table

索引
  1. class  AddCustomerNameIndexToOrders < ActiveRecord::Migration   
  2.      def   self .up   
  3.          add_index  :orders :name   
  4.      end   
  5.      def   self .down   
  6.          remove_index  :orders :name   
  7.      end   
  8. end   


PK
  1. create_table  :tickets :primary_key  =>  :ticket_number   do   |t |   
  2.     t.column  :created_at :timestamp   
  3.     t.column  :description :text   
  4. end   

raise ActiveRecord::IrreversibleMigration 不可逆错误
  1. class  ChangeOrderTypeToString < ActiveRecord::Migration   
  2.      def   self .up   
  3.         change_column  :orders :order_type :string :null  =>  false   
  4.      end   
  5.      def   self .down   
  6.          raise  ActiveRecord::IrreversibleMigration   
  7.      end   
  8. end   


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics