`
cowoo
  • 浏览: 48039 次
  • 性别: Icon_minigender_1
社区版块
存档分类

Rails Migration

阅读更多
一直知道rails里面用migrate来进行数据库的版本控制,还是比较浅显易懂,做做笔记。

RoR的官方Wiki上有两篇文章:
http://wiki.rubyonrails.com/rails/pages/UnderstandingMigrations
http://wiki.rubyonrails.com/rails/pages/UsingMigrations


如何使用:
1. Create a migration
ruby 代码
  1. ruby script/generate migration description_of_migration  

命名提示:
a.Migration的命名规则和model,controller一样
b.给一个mingration取一个和已经有的model类一样的名字会导致rake db:migrate诡异地失败(??未测试)
 
2. Edit the code to tell it what to do.

Edit the newly created file (in db/migrate). Define the up and a down methods.

3. Run the migration with Rake

ruby 代码
 
  1. rake db:migrate  


Tables
create_table
一个ID字段(主健)会被自动创建,对于has_and_belongs_to_many表来说,可以用:id=>false来取消


 
ruby 代码
 
  1. class AddTags < ActiveRecord::Migration  
  2.     def self.up  
  3.       create_table :images_tags:id => false do |table|  
  4.         table.column :image_id:integer  
  5.         table.column :tag_id:integer  
  6.       end  
  7.       create_table :tags do |table|  
  8.         table.column :name:string  
  9.       end  
  10.     end  
  11.   
  12.     def self.down  
  13.       drop_table :tags  
  14.       drop_table :images_tags  
  15.     end  
  16.   end  

 
合法的字段类型包括:integer, float, datetime, date, timestamp, time, text, string, binary, and boolean. 合法的字段选项包括:limit, null (比如说 :null => false 表示 NOT NULL), 以及 default (来设定默认值).

create_table可以有很多参数(见API参考)。有一个是options,可以将用原始的sql语句来添加到表后面作限制,比如说字符编码,表的类型等,比如:

ruby 代码
 
  1. create_table(:families:options => 'DEFAULT CHARSET=UTF8') do |t|  


 Columns
 Migrations work with columns in create_table and also with add_column.

 Options when running rake db:migrate

 Migrate to a specific version
ruby 代码
 
  1. rake db:migrate VERSION=17  

 
 Migrate a specific database
ruby 代码
 
  1. rake environment RAILS_ENV=production db:migrate  
分享到:
评论
3 楼 zgw06629 2009-02-04  
应在rails工程目录下
2 楼 xujun2008 2007-09-17  
运行rake出错,可能是rakefile的路径没找到.
你试试在rails应用的根目录下执行rake命令。
1 楼 gaofan 2007-07-26  
我运行rake就出错:
rake aborted!
no rakefile find

怎么回事啊

相关推荐

Global site tag (gtag.js) - Google Analytics