1.简介

在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
end def down
drop_table :products
end
end

上面就是一个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 => false
end
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_column
   add_index
   change_column
   change_table
   create_table
   drop_table
   remove_column
   remove_index
   rename_column

如果想回滚migration对数据库造成的改变,可以使用rake db:rollback命令。

1.2.ActiveRecord支持的列类型

:binary
   :boolean
   :date
   :datetime
   :decimal
   :float
   :integer
   :primary_key
   :string
   :text
   :time
   :timestamp

2.创建migration

2.1.创建model

rails generate model Product name:string description:text

创建的migration文件位于db/migrate目录,文件名称为yyyymmddmmss_create_products.rb。

class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description t.timestamps
end
end
end

2.2.创建单独的migration

rails generate migration AddPartNumberToProduct

class AddPartNumberToProducts < ActiveRecord::Migration
def change
end
end

指定列的名称

rails generate migration AddPartNumberToProduct part_number:string

class AddPartNumberToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
end
end

删除列
   rails generate migration RemovePartNumberToProduct part_number:string

class RemovePartNumberFromProducts < ActiveRecord::Migration
def up
remove_column :products, :part_number
end def down
add_column :products, :part_number, :string
end
end

还可以添加多个列

rails generate migration AddDetailsToProducts part_number:string price:decimal

class AddDetailsToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
add_column :products, :price, :decimal
end
end

3.编写mirgation

3.1.创建表

create_table :products do |t| 

  t.string :name 

end 

create_table :products do |t| 

  t.column :name, :string, :null => false

end

如果数据库是mysql,还可以通过下面的语句指定使用的引擎,mysql默认的引擎是InnoDB。

create_table :products, :options => "ENGINE=MyISAM" do |t|
t.string :name, :null => false
end

3.2.修改表结构

change_table :products do |t|
t.remove :description, :name
t.string :part_number
t.index :part_number
t.rename :upccode, :upc_code
end

删除name,description字段,添加part_number字段,在part_number字段建立索引,重命名upccode为upc_code。

3.3.辅助工具

t.timestamps可以自动添加created_at 和 updated_at列。

#创建表的同时添加
create_table :products do |t|
t.timestamps
end #给已经存在的表添加
change_table :products do |t|
t.timestamps
end

还有一个帮助工具references,用来指明表的外键关系。

create_table :products do |t|
t.references :category
end

上面的代码会在products表中添加一个外键字段category_id。

create_table :products do |t|
t.references :attachment, :polymorphic => {:default => 'Photo'}
end

上面的代码不仅会在products表中添加外键字段attachment_id,还会添加attachment_type字段,string类型,默认值是Photo。

rails之 Migrations (转)的更多相关文章

  1. rails使用 rake db:migrate 提示 Migrations are pending; run 'rake db:migrate RAILS_ENV=development' to resolve this issue.

    首先得特么建立数据库 : rake db:create 实际问题是没有int应该用integer http://www.rubycc.com/column/rails3.2.3/rails.htm

  2. 脱离rails 使用Active Record

    目录结构 database.yml development: adapter: sqlite3 database: db/test.db pool: 5 timeout: 5000 001_schem ...

  3. rails跑通第一个demo

    rails -h 查看帮助 Usage: rails new APP_PATH [options] Options: -r, [--ruby=PATH] # Path to the Ruby bina ...

  4. Nginx + unicorn 运行多个Rails应用程序

    PS:第一次写的很详细,可惜发布失败,然后全没了,这是第二次,表示只贴代码,剩下的自己领悟好了,这就是所谓的一鼓作气再而衰吧,希望没有第三次. 版本: ruby 2.1.0 rails 4.0.2 n ...

  5. Rails当你运行一个数据库回滚错误:ActiveRecord::IrreversibleMigration exception

    最近rails3.2在更改数据库表字段,然后要回滚取消,但在运行rake db:rollback命令,错误: rake aborted! An error has occurred, all late ...

  6. RoR- Database setup& SQLite ... Migrations

    *rails uses SQLite for database by default *Built-in command-line DB viewer *Self-contained,server-l ...

  7. Ruby on Rails Mountable vs. Full Engine

    原文 :https://www.travisluong.com/ruby-on-rails-mountable-vs-full-engine/一个Rails Engine 本质是一个 Rails ap ...

  8. rails学习笔记: rake db 相关命令

    rails学习笔记: rake db 命令行 rake db:*****script/generate model task name:string priority:integer script/g ...

  9. go Rails 知识点,Concepts Series:url和parameter; 建立Rails App Templates;报错页面debug; counter_cache

    Rails Concepts Series: https://gorails.com/series/rails-concepts 基本都是免费的 一些细小的知识点,很有帮助. URL和paramete ...

随机推荐

  1. Linux内核内存管理子系统分析【转】

    本文转载自:http://blog.csdn.net/coding__madman/article/details/51298718 版权声明:本文为博主原创文章,未经博主允许不得转载. 还是那张熟悉 ...

  2. [转] 停止支持的老版本ubuntu源列表-old-releases

    我使用的是ubuntu 9.10,在网上找了大半个月之后,今天终于找到了可用的源地址.感谢这位cgjcgs仁兄. 点击阅读原文 ubuntu的普通版本支持的时间都有限,过了支持的时间,更新源都会被停用 ...

  3. WebClient与WebRequest差异

    WebRequst的使用 WebClient和HttpWebRequst是用来获取数据的2种方式,在我的这篇数据访问(2)中主要是讲的WebClient的使用,一般而言,WebClient更倾向于“按 ...

  4. Linux命令帮助中尖括号<>和方括号[]以及省略号...的含义

    在方括号内的表达式("[" 和 "]"之间的字符)是可选的(写命令时要去掉括号). 在尖括号内的表达式("[" 和 "]" ...

  5. [问题2014A10] 解答

    [问题2014A10]  解答 考虑如下变形: \[(I_n-A)^2=(AA'-A)(I_n-A)=A(A'-I_n)(I_n-A)=-A(I_n-A)'(I_n-A).\] 因为 \(A\) 是非 ...

  6. 查看SQL SERVER数据库运行参数和连接数

    ---查看当前数据库系统所有请求情况.我只列出了我认为比较重要有助于我解决问题的字段. SELECT ds.session_id, ds.status, Db_name(dr.database_id) ...

  7. 分享 - 最初的JDBC操作步骤

    /* * 1. 注册 */ // 装载注册 SQLServer Driver Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDri ...

  8. 解决lScrollView嵌套ListView只显示一行的问题,listvie显示全部的item

    ScrollView嵌套ListView只显示一行的问题 1.思路:给listview重新添加一个高度. listview的高度==listview.item的高度之和. 2.注意:关键是添加list ...

  9. iOS - C 应用

    前言 1)操作符两端必须加空格,(每行第一个赋值语句对齐). 2)变量名必须是英文(不能是拼音):英文.数字.下划线和美元符号. 3)等于号 == 反过来写(0 == i%4)防止少些赋值号的错误. ...

  10. IOS_改变UITextField placeHolder颜色、字体

    http://blog.sina.com.cn/s/blog_671d2e4f0101d90v.html