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   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值