ITeye博客

Rails Migration

cowoo · 2007-04-18 00:23 · Ruby on Rails · Markdown

一直知道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. def self.down
  12. drop_table :tags
  13. drop_table :images_tags
  14. end
  15. 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)

  1. #3 楼 · zgw06629 · 2009-02-04 14:46

    应在rails工程目录下

  2. #2 楼 · xujun2008 · 2007-09-17 19:42

    运行rake出错,可能是rakefile的路径没找到. 你试试在rails应用的根目录下执行rake命令。

  3. #1 楼 · gaofan · 2007-07-26 10:08

    我运行rake就出错: rake aborted! no rakefile find

    怎么回事啊

评论功能维护中,当前仅展示历史评论。